﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;//使用IO
using System.IO.Ports;
using System.Threading;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Net;//使用IPAddress
using System.Net.Sockets;

using Sunny.UI;

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;


namespace LaneLpnr.Forms
{
    using libvlc_media_t = System.IntPtr;
    using libvlc_media_player_t = System.IntPtr;
    using libvlc_instance_t = System.IntPtr;

    public partial class 车道视频监控 : UIPage
    {
        Autosize.AutoSizeFormClass asc = new Autosize.AutoSizeFormClass();

        public Common.DataObject[] dataInfoNo = new Common.DataObject[2];

        public Common.WriteLog Trace = new Common.WriteLog();

        udpc udptest = new udpc();

        public static List<Thread> ThreadList;//定义一个线程池

        public static Socket client;

        public IntPtr[] Lpnr_Handle = new IntPtr[2] { IntPtr.Zero, IntPtr.Zero };
        public IntPtr[] picturehWnd = new IntPtr[2] { IntPtr.Zero, IntPtr.Zero };
        public IntPtr[] H264_Handle = new IntPtr[2] { IntPtr.Zero, IntPtr.Zero };

        public bool[] vedioBit = new bool[2] { false, false };

        public long[] H264_buff = new long[2] { 0, 0 };
        public int[] InitHvBit = new int[2] { 0, 0 };

        public int CloseHvBit = 1;

        public int Recognition_total = 0;
        public int Recognition_success_rate = 0;

        public string[] CameraIP = new string[2] { "", "" };
        public string[] ICECameraIP = new string[2] { "", "" };
        public string[] LaneIP = new string[2] { "", "" };
        public string[] IPCIP = new string[2] { "", "" };

        public static string GetManchineIPAddress = "";
        public string CameraLabel = "";

        public string lasttime;
        public string nowtime;

        public int softTriggerCount = 0;

        private const int WM_USER = 0x0400;      //272
        private const int WM_USER_2 = 0x0401;    //273
        private const int WM_USER_H264 = 0x0402; //274

        public static int MY_MSG_BEGIN = WM_USER + 100;
        public static int MY_MSG_BEGIN_2 = WM_USER_2 + 200;

        public static int MY_MSG_BEGIN_H264 = WM_USER_H264 + 300;
        public static int MY_MSG_BEGIN_H264_2 = WM_USER_H264 + 400;

        public static int MY_MSG_END = WM_USER + 101;
        public static int[] My_MSG_HANDLE = { 0, 0 };

        public bool _isgetplate = false;
        public bool _isgetlive = true;
        public bool _isreleasedata = true;

        public string planetAll = "";

        public bool enablequadbit = false;//输出车头图
        public bool enabletheadbit = false;//输出1/4图
        public bool enableallbit = false;//禁止输出抓拍全图
        public bool _isrecudp = true;

        public bool _issendudp = false;

        //public byte[] Wind_Run = new byte[19] { 0x01, 0x30, 0x31, 0x44, 0x4F, 0x50, 0x30, 0x46, 0x46, 0x20, 0x04, 0x01, 0x30, 0x31, 0x45, 0x52, 0x30, 0x28, 0x04 };
        //public byte[] Wind_Stop = new byte[19] { 0x01, 0x30, 0x31, 0x44, 0x4F, 0x50, 0x30, 0x30, 0x30, 0x54, 0x04, 0x01, 0x30, 0x31, 0x45, 0x52, 0x30, 0x28, 0x04 };


        //旧版 5510 设置工作模式MODBUS
        //public byte[] MODBUS_Mode = new byte[17] { 0x01, 0x46, 0x46, 0x54, 0x4D, 0x30, 0x31, 0x2E, 0x04, 0x01, 0x30, 0x31, 0x45, 0x52, 0x30, 0x28, 0x04 };

        //public byte[] Wind_Run = new byte[16] { 0x01 ,0x06 ,0x00 ,0x00 ,0x00 ,0x01 ,0x48 ,0x0A ,0x01 ,0x06 ,0x00 ,0x00 ,0x00 ,0x01 ,0x48 ,0x0A };
        //public byte[] Wind_Stop = new byte[16] { 0x01, 0x06, 0x00, 0x00, 0x00, 0x00, 0x89, 0xCA, 0x01, 0x06, 0x00, 0x00, 0x00, 0x00, 0x89, 0xCA };


        //新版5510-A
        public byte[] Wind_Run = new byte[8] { 0x01, 0x05, 0x00, 0x00, 0xFF, 0x00, 0x8C, 0x3A };
        public byte[] Wind_Stop = new byte[8] { 0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0xCD, 0xCA };

        public static 车道视频监控 mainLPNR;

        public string lanetype = Common.ConfigHelper.GetConnectionStringConfig("Lanetype");

        public StringBuilder[] http_alb = new StringBuilder[4];

        public string[] LpnrIp = new string[12];
        public string[] LaneIp = new string[12];
        public string[] LaneName = new string[12];
        public bool[] feeltbit = new bool[12];


        private bool work_run = false;
        private bool park_work_run = false;
        public bool _timebit = false;
        public bool _statebit = false;
        public bool _headTailbit = false;

        private static List<Common.Lyg_SendData.Lyg_ParkingDataInfo> Lyg_ParkDataPool = new List<Common.Lyg_SendData.Lyg_ParkingDataInfo>();


        public string vehicleType ="";
        public void http_alb_ctrl_Init()
        {
            try
            {
                StringBuilder[] str = new StringBuilder[4];
                str[0] = new StringBuilder();
                str[0].Append("{");
                str[0].Append("\"type\":\"" + "alb_open" + "\"");
                str[0].Append("}");
                http_alb[0] = str[0];

                str[1] = new StringBuilder();
                str[1].Append("{");
                str[1].Append("\"type\":\"" + "alb_close" + "\"");
                str[1].Append("}");
                http_alb[1] = str[1];

                str[2] = new StringBuilder();
                str[2].Append("{");
                str[2].Append("\"type\":\"" + "queue_open" + "\"");
                str[2].Append("}");
                http_alb[2] = str[2];

                str[3] = new StringBuilder();
                str[3].Append("{");
                str[3].Append("\"type\":\"" + "queue_close" + "\"");
                str[3].Append("}");
                http_alb[3] = str[3];
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常http_alb_ctrl_Init" + ex.ToString());
            }
        }

        /// <summary>
        /// 华夏参数
        /// </summary>
        /// 
        private int[] count = new int[4] { 0, 0, 0, 0 };
        private long totalCount = 0;

        private int MAX_OSD_TEXT = 64;
        public Ice_Camsdk.ICE_OSDAttr_S osdInfo = new Ice_Camsdk.ICE_OSDAttr_S();
        public Ice_Camsdk.ICE_VBR_RESULT_S vbrResult = new Ice_Camsdk.ICE_VBR_RESULT_S();
        public Ice_Camsdk.ICE_VDC_PICTRUE_INFO_S vdcInfo = new Ice_Camsdk.ICE_VDC_PICTRUE_INFO_S();
        public Ice_Camsdk.ICE_VLPR_OUTPUT_S vlprInfo = new Ice_Camsdk.ICE_VLPR_OUTPUT_S();


        Mutex mutex = new Mutex();
        Mutex mutexThread = new Mutex();
        public static Thread[] mythread = new Thread[4] { null, null, null, null };
        public static Thread threadTrigger = null;
        public static Thread threadOpenGate = null;
        public static Thread threadStatus = null;
        public static Thread threadOpenGate2 = null;
        public static Thread threadRS485 = null;
        public static Thread threadRS232 = null;
        public static Thread[] threadBroadcast = new Thread[4] { null, null, null, null };

        private string[] strVehicleColor_old = new string[] { "未知", "红色", "绿色", "蓝色", "黄色", "白色", "灰色", "黑色", "紫色", "棕色", "粉色" };
        private string[] strVehicleColor = new string[] {
            "未知",
            "黑色",
            "蓝色",
            "灰色",
            "棕色",
            "绿色",
            "夜间深色",
            "紫色",
            "红色",
            "白色",
            "黄色" };

        private string[] strAlarmType = new string[]{
            "实时_硬触发",
            "实时_视频触发",
            "实时_软触发",
            "实时_硬触发",
            "实时_视频触发",
            "实时_软触发",
            "实时_硬触发",
            "实时_视频触发",
            "实时_软触发",
            "脱机_硬触发",
            "脱机_视频触发",
            "脱机_软触发",
            "脱机_硬触发",
            "脱机_视频触发",
            "脱机_软触发",
            "脱机_硬触发",
            "脱机_视频触发",
            "脱机_软触发",
            "实时_硬触发",
            "实时_视频触发",
            "实时_软触发",
            "脱机_硬触发",
            "脱机_视频触发",
            "脱机_软触发"
        };


        private string[] strVehicleType = new string[]
        {
            "未知",
            "轿车",
            "面包车",
            "大型客车",
            "中型客车",
            "皮卡",
            "非机动车",
            "SUV",
            "MPV",
            "微型货车",
            "轻型货车",
            "中型货车",
            "重型货车"
        };

        //设置变量
        private string m_strStorePath = Common.ConfigHelper.GetConnectionStringConfig("ImagePath");

        public delegate void UpdatePlateInfo(string strIP, string strNum, string strColor, uint nVehicleColor,
            uint nAlarmType, short nVehiclType, uint nCapTime, int index, string strLogName, Ice_Camsdk.ICE_RECT_S stVlprInfo);
        public UpdatePlateInfo updatePlateInfo;
        public delegate void UpdateStatus(int index, int type);
        public UpdateStatus updateStatus;
        public delegate void UpdateTriggerStatus(int index, uint nStatus);
        public UpdateTriggerStatus triggerStatus;
        public delegate void UpdatePortInfo(string strIp, uint len, int index, string data, int type);
        public UpdatePortInfo updatePortInfo;
        public delegate void UpdateDeviceEvent(string strIP, uint nType, uint ndata1, uint ndata2, uint ndata3, uint ndata4, int nFlag, int road);
        public UpdateDeviceEvent updateDeviceEvent;


        private IntPtr[] pUid = new IntPtr[4] { IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero };
        private bool[] bClose = new bool[4] { false, false, false, false };


        /// <summary>
        /// rtsp网络视频
        /// </summary>
        internal struct PointerToArrayOfPointerHelper
        {
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 11)]
            public IntPtr[] pointers;
        }

        //vlc库启动参数配置  
        private static string pluginPath = System.Environment.CurrentDirectory + "\\plugins\\";
        // private static string pluginPath = "D:\\VLCTools\\plugins\\";
        private static string plugin_arg = "--plugin-path=" + pluginPath;

        //用于播放节目时，转录节目  
        //private static string program_arg = "--sout=#duplicate{dst=std{access=file,mux=ts,dst=d:/test.ts}}";  
        private static string[] arguments = { "-I", "dummy", "--ignore-config", "--video-title", plugin_arg };//, program_arg };  
                                                                                                              //private static string[] arguments = { "--verbose=2", "--network-caching=300", "--no-snapshot-preview" ,plugin_arg};

        #region 私有变量
        private libvlc_instance_t lit;
        private libvlc_media_player_t lmpt;
        #endregion
        #region 公有函数
        /// <summary>
        /// 播放网络视频流
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="handle">显示控件句柄</param>
        /// <returns>true：播放成功；false：播放失败</returns>
        public bool playUrl(string url, IntPtr handle)
        {
            lit = Create_Media_Instance();
            lmpt = Create_MediaPlayer(lit, handle);
            //播放网络视频
            return NetWork_Media_Play(lit, lmpt, url);
            //播放本地视频
            // return Local_Media_Play(lit, lmpt, url);
        }
        /// <summary>
        /// 播放本地视频
        /// </summary>
        /// <param name="path">视频路径</param>
        /// <param name="handle">显示控件句柄</param>
        /// <returns>true：播放成功；false：播放失败</returns>
        public bool playLocalVideo(string path, IntPtr handle)
        {
            lit = Create_Media_Instance();
            lmpt = Create_MediaPlayer(lit, handle);
            return Local_Media_Play(lit, lmpt, path);
        }
        /// <summary>
        /// 释放VLC资源
        /// </summary>
        /// <returns>true：释放；false：失败</returns>
        public bool release()
        {
            try
            {
                MediaPlayer_Stop(lmpt);
                // Release_Media_Instance(lit);
                Release_MediaPlayer(lmpt);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 是否正在播放
        /// </summary>
        /// <returns></returns>
        public bool IsPlaying()
        {
            return MediaPlayer_IsPlaying(lmpt);
        }
        /// <summary>
        /// 停止播放
        /// </summary>
        public void Stop()
        {
            MediaPlayer_Stop(lmpt);
        }
        /// <summary>
        /// 获得视频时长
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public double Durations(string url)
        {
            return Duration(lit, url);
        }

        /// <summary>
        /// 暂停播放
        /// </summary>
        public void Pause()
        {
            MediaPlayer_Pause(lmpt);
        }
        /// <summary>
        /// 播放
        /// </summary>
        public void PlayU()
        {
            Play(lmpt);
        }
        /// <summary>
        /// 设置播放时间
        /// </summary>
        /// <param name="seekTime"></param>
        public void SetTime(double seekTime)
        {
            if (lmpt != IntPtr.Zero)
            {
                libvlc.SafeNativeMethods.libvlc_media_player_set_time(lmpt, (Int64)seekTime * 1000);
            }
        }
        public void Aspect(string aspects)
        {
            if (lmpt != IntPtr.Zero)
            {
                libvlc.SafeNativeMethods.libvlc_video_set_aspect_ratio(lmpt, aspects.ToCharArray());
            }
        }
        /// <summary>
        /// 获得播放时间
        /// </summary>
        /// <returns></returns>
        public double GetTime()
        {
            double seekTime = 0;
            if (lmpt != IntPtr.Zero)
            {
                seekTime = libvlc.SafeNativeMethods.libvlc_media_player_get_time(lmpt);
            }
            return seekTime;
        }
        /// <summary>
        ///获取屏幕参数
        /// </summary>
        /// <returns></returns>
        public int GetFullscreen()
        {
            return libvlc.SafeNativeMethods.libvlc_get_fullscreen(lmpt);
        }
        public bool SetFullscreen(int screen)
        {
            return SetFullScreen(lmpt, screen);
        }
        /// <summary>
        /// 录制快照
        /// </summary>
        /// <param name="path"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool TakeSnapshots(string path, string name)
        {
            return TakeSnapShot(lmpt, path, name);
        }
        #endregion
        #region 私有函数
        /// <summary>  
        /// 创建VLC播放资源索引  
        /// </summary>  
        /// <param name="arguments"></param>  
        /// <returns></returns>  
        private libvlc_instance_t Create_Media_Instance()
        {
            libvlc_instance_t libvlc_instance = IntPtr.Zero;
            IntPtr argvPtr = IntPtr.Zero;

            try
            {
                if (arguments.Length == 0 ||
                    arguments == null)
                {
                    return IntPtr.Zero;
                }

                //将string数组转换为指针  
                argvPtr = StrToIntPtr(arguments);
                if (argvPtr == null || argvPtr == IntPtr.Zero)
                {
                    return IntPtr.Zero;
                }

                //设置启动参数  
                libvlc_instance = libvlc.SafeNativeMethods.libvlc_new(arguments.Length, argvPtr);
                if (libvlc_instance == null || libvlc_instance == IntPtr.Zero)
                {
                    return IntPtr.Zero;
                }

                return libvlc_instance;
            }
            catch
            {
                return IntPtr.Zero;
            }
        }

        /// <summary>  
        /// 释放VLC播放资源索引  
        /// </summary>  
        /// <param name="libvlc_instance">VLC 全局变量</param>  
        private void Release_Media_Instance(libvlc_instance_t libvlc_instance)
        {
            try
            {
                if (libvlc_instance != IntPtr.Zero ||
                    libvlc_instance != null)
                {
                    libvlc.SafeNativeMethods.libvlc_release(libvlc_instance);
                }

                libvlc_instance = IntPtr.Zero;
            }
            catch (Exception)
            {
                libvlc_instance = IntPtr.Zero;
            }
        }

        /// <summary>  
        /// 创建VLC播放器  
        /// </summary>  
        /// <param name="libvlc_instance">VLC 全局变量</param>  
        /// <param name="handle">VLC MediaPlayer需要绑定显示的窗体句柄</param>  
        /// <returns></returns>  
        private libvlc_media_player_t Create_MediaPlayer(libvlc_instance_t libvlc_instance, IntPtr handle)
        {
            libvlc_media_player_t libvlc_media_player = IntPtr.Zero;

            try
            {
                if (libvlc_instance == IntPtr.Zero ||
                    libvlc_instance == null ||
                    handle == IntPtr.Zero ||
                    handle == null)
                {
                    return IntPtr.Zero;
                }

                //创建播放器  
                libvlc_media_player = libvlc.SafeNativeMethods.libvlc_media_player_new(libvlc_instance);
                if (libvlc_media_player == null || libvlc_media_player == IntPtr.Zero)
                {
                    return IntPtr.Zero;
                }

                //设置播放窗口              
                libvlc.SafeNativeMethods.libvlc_media_player_set_hwnd(libvlc_media_player, (int)handle);

                return libvlc_media_player;
            }
            catch
            {
                libvlc.SafeNativeMethods.libvlc_media_player_release(libvlc_media_player);

                return IntPtr.Zero;
            }
        }

        /// <summary>  
        /// 释放媒体播放器  
        /// </summary>  
        /// <param name="libvlc_media_player">VLC MediaPlayer变量</param>  
        private void Release_MediaPlayer(libvlc_media_player_t libvlc_media_player)
        {
            try
            {
                if (libvlc_media_player != IntPtr.Zero ||
                    libvlc_media_player != null)
                {
                    if (libvlc.SafeNativeMethods.libvlc_media_player_is_playing(libvlc_media_player))
                    {
                        libvlc.SafeNativeMethods.libvlc_media_player_stop(libvlc_media_player);
                    }

                    libvlc.SafeNativeMethods.libvlc_media_player_release(libvlc_media_player);
                }

                libvlc_media_player = IntPtr.Zero;
            }
            catch (Exception)
            {
                libvlc_media_player = IntPtr.Zero;
            }
        }

        /// <summary>  
        /// 播放网络媒体  
        /// </summary>  
        /// <param name="libvlc_instance">VLC 全局变量</param>  
        /// <param name="libvlc_media_player">VLC MediaPlayer变量</param>  
        /// <param name="url">网络视频URL，支持http、rtp、udp等格式的URL播放</param>  
        /// <returns></returns>  
        private bool NetWork_Media_Play(libvlc_instance_t libvlc_instance, libvlc_media_player_t libvlc_media_player, string url)
        {
            IntPtr pMrl = IntPtr.Zero;
            libvlc_media_t libvlc_media = IntPtr.Zero;

            try
            {
                if (url == null ||
                    libvlc_instance == IntPtr.Zero ||
                    libvlc_instance == null ||
                    libvlc_media_player == IntPtr.Zero ||
                    libvlc_media_player == null)
                {
                    return false;
                }

                pMrl = StrToIntPtr(url);
                if (pMrl == null || pMrl == IntPtr.Zero)
                {
                    return false;
                }

                //播放网络文件  
                libvlc_media = libvlc.SafeNativeMethods.libvlc_media_new_location(libvlc_instance, pMrl);

                if (libvlc_media == null || libvlc_media == IntPtr.Zero)
                {
                    return false;
                }

                //将Media绑定到播放器上  
                libvlc.SafeNativeMethods.libvlc_media_player_set_media(libvlc_media_player, libvlc_media);

                //释放libvlc_media资源  
                libvlc.SafeNativeMethods.libvlc_media_release(libvlc_media);
                libvlc_media = IntPtr.Zero;

                if (0 != libvlc.SafeNativeMethods.libvlc_media_player_play(libvlc_media_player))
                {
                    return false;
                }

                //休眠指定时间  
                Thread.Sleep(500);

                return true;
            }
            catch (Exception)
            {
                //释放libvlc_media资源  
                if (libvlc_media != IntPtr.Zero)
                {
                    libvlc.SafeNativeMethods.libvlc_media_release(libvlc_media);
                }
                libvlc_media = IntPtr.Zero;

                return false;
            }
        }
        /// <summary>
        /// 获得视频时间
        /// </summary>
        /// <param name="libvlc_instance"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private double Duration(libvlc_instance_t libvlc_instance, string url)
        {
            double duration_ = 0;
            libvlc_media_t libvlc_media = IntPtr.Zero;
            IntPtr pMrl = IntPtr.Zero;
            pMrl = StrToIntPtr(url);
            if (pMrl == null || pMrl == IntPtr.Zero)
            {
                return duration_;
            }
            libvlc_media = libvlc.SafeNativeMethods.libvlc_media_new_path(libvlc_instance, pMrl);
            libvlc.SafeNativeMethods.libvlc_media_parse(libvlc_media);
            duration_ = libvlc.SafeNativeMethods.libvlc_media_get_duration(libvlc_media);
            return duration_;
        }

        /// <summary>
        /// 播放本地视频
        /// </summary>
        /// <param name="libvlc_instance"></param>
        /// <param name="libvlc_media_player"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private bool Local_Media_Play(libvlc_instance_t libvlc_instance, libvlc_media_player_t libvlc_media_player, string url)
        {
            IntPtr pMrl = IntPtr.Zero;
            libvlc_media_t libvlc_media = IntPtr.Zero;

            try
            {
                if (url == null ||
                    libvlc_instance == IntPtr.Zero ||
                    libvlc_instance == null ||
                    libvlc_media_player == IntPtr.Zero ||
                    libvlc_media_player == null)
                {
                    return false;
                }

                pMrl = StrToIntPtr(url);
                if (pMrl == null || pMrl == IntPtr.Zero)
                {
                    return false;
                }

                //播放本地视频  
                libvlc_media = libvlc.SafeNativeMethods.libvlc_media_new_path(libvlc_instance, pMrl);

                if (libvlc_media == null || libvlc_media == IntPtr.Zero)
                {
                    return false;
                }

                //将Media绑定到播放器上  
                libvlc.SafeNativeMethods.libvlc_media_player_set_media(libvlc_media_player, libvlc_media);

                //释放libvlc_media资源  
                libvlc.SafeNativeMethods.libvlc_media_release(libvlc_media);
                libvlc_media = IntPtr.Zero;

                if (0 != libvlc.SafeNativeMethods.libvlc_media_player_play(libvlc_media_player))
                {
                    return false;
                }

                //休眠指定时间  
                Thread.Sleep(500);

                return true;
            }
            catch (Exception)
            {
                //释放libvlc_media资源  
                if (libvlc_media != IntPtr.Zero)
                {
                    libvlc.SafeNativeMethods.libvlc_media_release(libvlc_media);
                }
                libvlc_media = IntPtr.Zero;

                return false;
            }
        }

        /// <summary>  
        /// 暂停或恢复视频  
        /// </summary>  
        /// <param name="libvlc_media_player">VLC MediaPlayer变量</param>  
        /// <returns></returns>  
        private bool MediaPlayer_Pause(libvlc_media_player_t libvlc_media_player)
        {
            try
            {
                if (libvlc_media_player == IntPtr.Zero ||
                    libvlc_media_player == null)
                {
                    return false;
                }

                if (libvlc.SafeNativeMethods.libvlc_media_player_can_pause(libvlc_media_player))
                {
                    libvlc.SafeNativeMethods.libvlc_media_player_pause(libvlc_media_player);

                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>  
        /// 停止播放  
        /// </summary>  
        /// <param name="libvlc_media_player">VLC MediaPlayer变量</param>  
        /// <returns></returns>  
        private bool MediaPlayer_Stop(libvlc_media_player_t libvlc_media_player)
        {
            try
            {
                if (libvlc_media_player == IntPtr.Zero ||
                    libvlc_media_player == null)
                {
                    return false;
                }

                if (libvlc_media_player != null)
                {
                    libvlc.SafeNativeMethods.libvlc_media_player_stop(libvlc_media_player);
                    libvlc_media_player = IntPtr.Zero;
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>  
        /// VLC MediaPlayer是否在播放  
        /// </summary>  
        /// <param name="libvlc_media_player">VLC MediaPlayer变量</param>  
        /// <returns></returns>  
        private bool MediaPlayer_IsPlaying(libvlc_media_player_t libvlc_media_player)
        {
            try
            {
                if (libvlc_media_player == IntPtr.Zero ||
                    libvlc_media_player == null)
                {
                    return false;
                }

                return libvlc.SafeNativeMethods.libvlc_media_player_is_playing(libvlc_media_player);
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>  
        /// 录制快照  
        /// </summary>  
        /// <param name="libvlc_media_player">VLC MediaPlayer变量</param>  
        /// <param name="path">快照要存放的路径</param>  
        /// <param name="name">快照保存的文件名称</param>  
        /// <returns></returns>  
        private bool TakeSnapShot(libvlc_media_player_t libvlc_media_player, string path, string name)
        {
            try
            {
                string snap_shot_path = null;

                if (libvlc_media_player == IntPtr.Zero ||
                    libvlc_media_player == null)
                {
                    return false;
                }

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                snap_shot_path = path + "\\" + name;

                if (0 == libvlc.SafeNativeMethods.libvlc_video_take_snapshot(libvlc_media_player, 0, snap_shot_path.ToCharArray(), 0, 0))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>  
        /// 获取信息  
        /// </summary>  
        /// <param name="libvlc_media_player"></param>  
        /// <returns></returns>  
        private bool GetMedia(libvlc_media_player_t libvlc_media_player)
        {
            libvlc_media_t media = IntPtr.Zero;

            try
            {
                if (libvlc_media_player == IntPtr.Zero ||
                    libvlc_media_player == null)
                {
                    return false;
                }

                media = libvlc.SafeNativeMethods.libvlc_media_player_get_media(libvlc_media_player);
                if (media == IntPtr.Zero || media == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>  
        /// 获取已经显示的图片数  
        /// </summary>  
        /// <param name="libvlc_media_player"></param>  
        /// <returns></returns>  
        private int GetDisplayedPictures(libvlc_media_player_t libvlc_media_player)
        {
            libvlc_media_t media = IntPtr.Zero;
            libvlc.libvlc_media_stats_t media_stats = new libvlc.libvlc_media_stats_t();
            try
            {
                if (libvlc_media_player == IntPtr.Zero ||
                    libvlc_media_player == null)
                {
                    return 0;
                }

                media = libvlc.SafeNativeMethods.libvlc_media_player_get_media(libvlc_media_player);
                if (media == IntPtr.Zero || media == null)
                {
                    return 0;
                }

                if (1 == libvlc.SafeNativeMethods.libvlc_media_get_stats(media, ref media_stats))
                {
                    return media_stats.i_displayed_pictures;
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception)
            {
                return 0;
            }
        }

        /// <summary>  
        /// 设置全屏  
        /// </summary>  
        /// <param name="libvlc_media_player"></param>  
        /// <param name="isFullScreen"></param>  
        private bool SetFullScreen(libvlc_media_player_t libvlc_media_player, int isFullScreen)
        {
            try
            {
                if (libvlc_media_player == IntPtr.Zero ||
                    libvlc_media_player == null)
                {
                    return false;
                }

                libvlc.SafeNativeMethods.libvlc_set_fullscreen(libvlc_media_player, isFullScreen);

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// 恢复播放
        /// </summary>
        private void Play(libvlc_media_player_t libvlc_mediaplayer)
        {
            if (libvlc_mediaplayer != IntPtr.Zero)
            {
                libvlc.SafeNativeMethods.libvlc_media_player_play(libvlc_mediaplayer);
            }
        }
        //将string []转换为IntPtr  
        private static IntPtr StrToIntPtr(string[] args)
        {
            try
            {
                IntPtr ip_args = IntPtr.Zero;

                PointerToArrayOfPointerHelper argv = new PointerToArrayOfPointerHelper();
                argv.pointers = new IntPtr[11];

                for (int i = 0; i < args.Length; i++)
                {
                    argv.pointers[i] = Marshal.StringToHGlobalAnsi(args[i]);
                }

                int size = Marshal.SizeOf(typeof(PointerToArrayOfPointerHelper));
                ip_args = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(argv, ip_args, false);

                return ip_args;
            }
            catch (Exception)
            {
                return IntPtr.Zero;
            }
        }

        //将string转换为IntPtr  
        private static IntPtr StrToIntPtr(string url)
        {
            try
            {
                if (string.IsNullOrEmpty(url))
                {
                    return IntPtr.Zero;
                }

                IntPtr pMrl = IntPtr.Zero;
                byte[] bytes = Encoding.UTF8.GetBytes(url);

                pMrl = Marshal.AllocHGlobal(bytes.Length + 1);
                Marshal.Copy(bytes, 0, pMrl, bytes.Length);
                Marshal.WriteByte(pMrl, bytes.Length, 0);

                return pMrl;
            }
            catch (Exception)
            {
                return IntPtr.Zero;
            }
        }
        #endregion

        /// <summary>
        /// IPC网络相机初始化
        /// </summary>
        public void Vlc_Play_Init()
        {
            IPCIP[0] = uiComboBox_LpnrIpNo1.Text.Trim();
            string account = Common.ConfigHelper.GetConnectionStringConfig("Account");
            string password = Common.ConfigHelper.GetConnectionStringConfig("Password");

            if (Common.ConfigHelper.GetConnectionStringConfig("hasDaHua") == "yes")
            {
                string ip = IPCIP[0];
                if (LivecheckBox.Checked)
                {
                    //主码流
                    //playUrl("rtsp://" + account + ":" + password + "@" + ip + ":554/cam/realmonitor?channel=1&subtype=0", this.pictureBox_SnapImage1.Handle);
                    //副码流
                    playUrl("rtsp://" + account + ":" + password + "@" + ip + ":554/cam/realmonitor?channel=1&subtype=1", this.pictureBox_SnapImage1.Handle);

                    //Aspect("4:3");
                }
            }
            if (Common.ConfigHelper.GetConnectionStringConfig("hasHIKVISION") == "yes")
            {
                string ip = IPCIP[0];
                if (LivecheckBox.Checked)
                {
                    if (Common.ConfigHelper.GetConnectionStringConfig("hasHIKVISIONNew") == "0")
                    {
                        //副码流
                        playUrl("rtsp://" + account + ":" + password + "@" + ip + ":554/h264/ch1/sub/av_stream", this.pictureBox_SnapImage1.Handle);
                        //主码流
                        //playUrl("rtsp://" + account + ":" + password + "@" + ip + ":554/h264/ch1/main/av_stream", this.pictureBox_SnapImage1.Handle);
                        //Aspect("4:3");
                    }
                    else if (Common.ConfigHelper.GetConnectionStringConfig("hasHIKVISIONNew") == "1")
                    {
                        playUrl("rtsp://" + account + ":" + password + "@" + ip + "/Streaming/Channels/101", this.pictureBox_SnapImage1.Handle);
                        //Aspect("4:3");
                    }

                }

            }

            if (Common.ConfigHelper.GetConnectionStringConfig("hasXM") == "yes")
            {
                string ip = IPCIP[0];
                if (LivecheckBox.Checked)
                {
                    //副码流
                    playUrl("rtsp://" + ip + ":554/user=admin&password=&channel=1&stream=1.sdp?real_stream", this.pictureBox_SnapImage1.Handle);
                    //主码流
                    //playUrl("rtsp://192.168.1.10:554/user=admin&password=&channel=1&stream=1.sdp?real_stream", this.pictureBox_SnapImage1.Handle);
                    //Aspect("4:3");
                }

            }
            if (Common.ConfigHelper.GetConnectionStringConfig("haslpnrrtsp") == "yes")
            {
                string ip = IPCIP[0];
                if (LivecheckBox.Checked)
                {
                    playUrl("rtsp://" + ip + "/track1", this.pictureBox_VideoNo1.Handle);
                }
            }
        }


        /// <summary>
        /// IPC网络相机初始化
        /// </summary>
        public void Vlc_Play_Init_2()
        {
            IPCIP[1] = uiComboBox_LpnrIpNo2.Text.Trim();
            string account = Common.ConfigHelper.GetConnectionStringConfig("Account");
            string password = Common.ConfigHelper.GetConnectionStringConfig("Password");

            if (Common.ConfigHelper.GetConnectionStringConfig("hasDaHua") == "yes")
            {
                string ip = IPCIP[1];
                if (LivecheckBox_2.Checked)
                {
                    //playUrl("rtsp://" + account + ":" + password + "@" + ip + ":554/cam/realmonitor?channel=1&subtype=0", this.pictureBox_SnapImage2.Handle);

                    playUrl("rtsp://" + account + ":" + password + "@" + ip + ":554/cam/realmonitor?channel=1&subtype=1", this.pictureBox_SnapImage2.Handle);
                    //Aspect("4:3");
                }
            }
            if (Common.ConfigHelper.GetConnectionStringConfig("hasHIKVISION") == "yes")
            {
                string ip = IPCIP[1];
                if (LivecheckBox_2.Checked)
                {
                    if (Common.ConfigHelper.GetConnectionStringConfig("hasHIKVISIONNew") == "0")
                    {
                        //副码流
                        playUrl("rtsp://" + account + ":" + password + "@" + ip + ":554/h264/ch1/sub/av_stream", this.pictureBox_SnapImage2.Handle);
                        //主码流
                        //playUrl("rtsp://" + account + ":" + password + "@" + ip + ":554/h264/ch1/main/av_stream", this.pictureBox_SnapImage2.Handle);
                        //Aspect("4:3");
                    }
                    else if (Common.ConfigHelper.GetConnectionStringConfig("hasHIKVISIONNew") == "1")
                    {
                        playUrl("rtsp://" + account + ":" + password + "@" + ip + ":554/Streaming/Channels/101", this.pictureBox_SnapImage2.Handle);
                        //Aspect("4:3");
                    }

                }

            }
            if (Common.ConfigHelper.GetConnectionStringConfig("hasXM") == "yes")
            {
                string ip = IPCIP[1];
                if (LivecheckBox_2.Checked)
                {
                    //副码流
                    playUrl("rtsp://" + ip + ":554/user=admin&password=&channel=1&stream=1.sdp?real_stream", this.pictureBox_SnapImage1.Handle);
                    //主码流
                    //playUrl("rtsp://192.168.1.10:554/user=admin&password=&channel=1&stream=1.sdp?real_stream", this.pictureBox_SnapImage1.Handle);
                    //Aspect("4:3");
                }
            }

            if (Common.ConfigHelper.GetConnectionStringConfig("haslpnrrtsp") == "yes")
            {
                string ip = IPCIP[1];
                if (LivecheckBox_2.Checked)
                {
                    playUrl("rtsp://" + ip + "/track1", this.pictureBox_VideoNo2.Handle);
                }
            }
        }

        public static IntPtr WelcomeLedIphwnd = IntPtr.Zero;

        public static bool HasWelcomeLedBit = false;
        public static bool HasParkingLedBit = false;
        public bool WelcomeLedOpenBit = false;
        public bool ParkingLedOpenBit = false;

        /// <summary>
        /// 费显初始化
        /// </summary>
        private void WelcomeLedInit()
        {
            string ledip = Common.ConfigHelper.GetConnectionStringConfig("WelcomeLedIp");
            string hasled = Common.ConfigHelper.GetConnectionStringConfig("hasWelcomeLed");
            if (hasled == "yes" && ledip != string.Empty)
            {
                HasWelcomeLedBit = true;
                if (WelcomeLedIphwnd == IntPtr.Zero)
                {
                    WelcomeLedIphwnd = Led.TFIProgram.TFI_Create();
                    if (WelcomeLedIphwnd != IntPtr.Zero)
                    {
                        WelcomeLedOpenBit = Led.TFIProgram.TFI_OpenNet(WelcomeLedIphwnd, ledip);
                        if (WelcomeLedOpenBit == true)
                        {
                            FlashLog.FlashLogger.Info("欢迎语费显初始化成功！");
                            Led.TFIInit.LedWelcomeInit();
                        }
                        else
                        {
                            FlashLog.FlashLogger.Info("欢迎语费显初始化失败！");
                        }
                        //Led.TFIProgram.TFI_SendVoice(WelcomeLedIphwnd, "欢迎光临");
                    }
                }
            }
            else if (hasled == "no" || hasled == string.Empty)
            {
                HasWelcomeLedBit = false;
            }
        }




        /// <summary>
        /// 标准停车场上报数据工作线程
        /// </summary>
        public void ParkWorkThreadInit()
        {
            Thread park_work_thread = new Thread(new ThreadStart(Park_Upload_Work_Thread));
            ThreadList.Add(park_work_thread);
            park_work_thread.IsBackground = true;
            park_work_thread.Start();
        }


        /// <summary>
        /// 停车场车牌数据上报工作主线程
        /// </summary>
        private void Park_Upload_Work_Thread()
        {
            while (park_work_run)
            {
                try
                {
                    if (Lyg_ParkDataPool.Count == 0)
                    {
                        Thread.Sleep(10);
                        continue;
                    }
                    Common.Lyg_SendData.Lyg_ParkingDataInfo obj = Lyg_ParkDataPool[0];

                    if (park_ready_upload(obj) == true)
                        {
                            FlashLog.FlashLogger.Info("数据上传成功!");

                            //lock (obj)
                            {
                                Lyg_ParkDataPool.RemoveAt(0);
                                FlashLog.FlashLogger.Info("删除队列数据, Now 队列个数 " + Lyg_ParkDataPool.Count.ToString() + "\r\n");
                            }
                        }
                        else
                        {
                            FlashLog.FlashLogger.Info("http连接异常，1s后再重新上传！");
                            Com.Delay.Delaym_new(1000);
                        }
                        Thread.Sleep(10);
                    
                }
                catch (NullReferenceException ex)
                {
                    FlashLog.FlashLogger.Error("异常 Upload_Work_Thread" + ex.ToString());
                }
            }
        }


        /// <summary>
        /// 数据上传
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool park_ready_upload(Common.Lyg_SendData.Lyg_ParkingDataInfo obj)
        {
            try
            {
                Encoding encoding = Encoding.GetEncoding("utf-8");

                if (postThreadMain(obj))
                {
                    return true;
                }
                else {
                    return false;
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Error("异常park_ready_upload" + ex.ToString());
                return false;
            }
        }


        /// <summary>
        /// 停车场车牌队列数据更新
        /// </summary>
        /// <param name="obj"></param>
        private static void NewTaskPark(Common.Lyg_SendData.Lyg_ParkingDataInfo obj)
        {
            try
            {
                //lock (obj)
                {
                    FlashLog.FlashLogger.Info("Last DataObject Count Is " + Lyg_ParkDataPool.Count.ToString());
                    while (Lyg_ParkDataPool.Count > 2)
                    {
                        FlashLog.FlashLogger.Info("队列数据大于2， 删除队尾数据");

                        // TOOD　删除DataPool队列头数据并记录
                        Lyg_ParkDataPool.RemoveRange(Lyg_ParkDataPool.Count - 2, Lyg_ParkDataPool.Count - 1);
                        FlashLog.FlashLogger.Info("删除队尾数据");
                    }

                    Lyg_ParkDataPool.Add(obj);
                    FlashLog.FlashLogger.Info("Now this DataObject count is " + Lyg_ParkDataPool.Count.ToString());
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Error("异常NewTaskPark" + ex.ToString());
            }
        }


        /// <summary>
        /// 标准停车场协议数据 在需要上报的地方使用该方法
        /// </summary>
        /// <param name="parkInfo"></param>
        public static bool SendParkData(Common.Lyg_SendData.Lyg_ParkingDataInfo parkInfo)
        {
            try
            {
                if (Common.ConfigHelper.GetConnectionStringConfig("hasUpload") == "no")
                {
                    FlashLog.FlashLogger.Info("《未使能上报功能，不上报车辆信息数据》" + "\r\n");
                    return false;
                }

                else if (Common.ConfigHelper.GetConnectionStringConfig("hasUploadNoPlate") == "no")
                {
                    if (parkInfo.plate.Contains("无"))
                    {
                        FlashLog.FlashLogger.Info("《未使能上报无车牌功能，不上报车辆信息数据》" + "\r\n");
                        return false;
                    }
                    else
                    {
                        NewTaskPark(parkInfo);
                    }
                }

                else
                {
                    NewTaskPark(parkInfo);
                }

                if (parkInfo.plateColor != "无")// 如果识别颜色不为空 则识别成功返回true
                {
                    return true;
                }
                return false;
            }

            catch (Exception ex)
            {
                FlashLog.FlashLogger.Error("异常NewThreadGetandSend " + ex.ToString());
                return false;
            }
        }



        public 车道视频监控()
        {
            InitializeComponent();
            mainLPNR = this;
            try
            {
                //this.BackgroundImage = imageList.Images[0];
            }
            catch (Exception ex)
            {
                throw new Exception("图片加载失败" + ex.Message.ToString());
            }
        }

        private void 车道视频监控_Load(object sender, EventArgs e)
        {
            asc.controllInitializeSize(this);

            try
            {
                Control_Init();//控件初始化

                ThreadList = new List<Thread>();

                IceCame_Init_All();
                WelcomeLedInit();

                if (lanetype == "0")
                {
                    //车道udp监听
                    udptest.StartUdpReceive();
                }
                else if (lanetype == "1")
                {
                    http_alb_ctrl_Init();
                }
                //车牌识别数据上报
                if (Common.ConfigHelper.GetConnectionStringConfig("hasUpload") == "yes")
                {
                    park_work_run = true;
                    ParkWorkThreadInit();
                }
                //加入开机自动启动程序
                if (Common.ConfigHelper.GetConnectionStringConfig("Autorun") == "1")
                {
                    Com.Delay.Delaym_new(500);//加载后延时0.5s连接加载
                    Link_InitButton_Click(sender, e);

                    Com.Delay.Delaym_new(1000);//初始化后延时0.5s连接启动
                    Link_Init_2Button_Click(sender, e);
                }
            
            
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("LPNRTool_Load" + ex.Message.ToString());
            }
        }


        /// <summary>
        /// 创建弹窗显示线程--该方法有异常
        /// </summary>
        /// <param name="str"></param>
        public void CreatePrcessBarThread(string str)
        {
            try
            {
                //实例化ThreadWithState类，为线程提供参数
                ThreadWithState tws = new ThreadWithState(str, 0);

                // 创建执行任务的线程，并执行
                Thread t = new Thread(new ThreadStart(tws.ThreadProc));
                t.Start();
                FlashLog.FlashLogger.Info("Main thread does some work, then waits.");
                t.Join();
            }
            catch (Exception ex)
            { FlashLog.FlashLogger.Debug("Exception CreatePrcessBarThread " + ex.ToString()); }
        }



        private void Link_InitButton_Click(object sender, EventArgs e)
        {
            if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "0")
            {
                LPNR_Init();
            }
            if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "1")
            {
                IceCame_Init();
            }
            Vlc_Play_Init();


            

        }

        private void Link_Init_2Button_Click(object sender, EventArgs e)
        {
            if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "0")
            {
                LPNR_Init_2();
            }
            if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "1")
            {
                IceCame_Init_2();
            }
            Vlc_Play_Init_2();
        }

        private void 车道视频监控_SizeChanged(object sender, EventArgs e)
        {
            asc.controlAutoSize(this);
            //this.WindowState = (System.Windows.Forms.FormWindowState)(2);//记录完控件的初始位置和大小后，再最大化
        }

        public void Control_Init()
        {
            //数据初始化 实例
            for (int i = 0; i < 2; i++)
            {
                dataInfoNo[i] = new Common.DataObject();
            }

            for (int i = 0; i < 2; i++)
            {
                LpnrIp[i] = Common.ConfigHelper.GetConnectionStringConfig("VechileIp_" + (i + 1).ToString());
                LaneIp[i] = Common.ConfigHelper.GetConnectionStringConfig("LaneIp_" + (i + 1).ToString());
                LaneName[i] = Common.ConfigHelper.GetConnectionStringConfig("LaneName_" + (i + 1).ToString());
            }

            uiComboBox_LpnrIpNo1.Text = LpnrIp[0];
            uiComboBox_LpnrIpNo2.Text = LpnrIp[1];

            uiTitlePanel_VideoNo1.Text = LaneName[0];
            uiTitlePanel_VideoNo2.Text = LaneName[1];

            //控件初始化

            uiDataGridView_laneNo1.AddColumn("序号", "serialNumber");
            uiDataGridView_laneNo1.AddColumn("触发时间", "triggerTime");
            //uiDataGridView_laneNo1.AddColumn("车牌颜色", "plateColor");
            uiDataGridView_laneNo1.AddColumn("车牌号", "plateNo");
            uiDataGridView_laneNo1.AddColumn("车辆类型", "vehicleType");
            uiDataGridView_laneNo1.AddColumn("备注", "remark");
            //所有列宽
            this.uiDataGridView_laneNo1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            //uiDataGridView_Init(uiDataGridView_laneNo1);

            uiDataGridView_laneNo2.AddColumn("序号", "serialNumber");
            uiDataGridView_laneNo2.AddColumn("触发时间", "triggerTime");
            //uiDataGridView_laneNo2.AddColumn("车牌颜色", "plateColor");
            uiDataGridView_laneNo2.AddColumn("车牌号", "plateNo");
            uiDataGridView_laneNo2.AddColumn("车辆类型", "vehicleType");
            uiDataGridView_laneNo2.AddColumn("备注", "remark");
            //所有列宽
            this.uiDataGridView_laneNo2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            //uiDataGridView_Init(uiDataGridView_laneNo2);
        }


        public void uiDataGridView_Init(Sunny.UI.UIDataGridView dgv)
        {
            int width = 0;
            //对于DataGridView的每一个列都调整
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                //将每一列都调整为自动适应模式
                dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                //记录整个DataGridView的宽度
                width += dgv.Columns[i].Width;
            }
            //判断调整后的宽度与原来设定的宽度的关系，如果是调整后的宽度大于原来设定的宽度，
            //则将DataGridView的列自动调整模式设置为显示的列即可，
            //如果是小于原来设定的宽度，将模式改为填充。
            if (width > dgv.Size.Width)
            {
                dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            }
            else
            {
                dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
            //冻结某列 从左开始 0，1，2
            dgv.Columns[0].Frozen = true;
        }


        /// </summary>
        public void LPNR_Init()
        {
            try
            {
                CameraIP[0] = uiComboBox_LpnrIpNo1.Text.Trim();
                IPAddress ip;
                if (IPAddress.TryParse(CameraIP[0], out ip))
                {

                    Lpnr_Handle[0] = Lpnr.LPNRProgram.LPNR_Init(CameraIP[0]);//初始化LPNRTool摄像机句柄

                    if (Lpnr_Handle[0] != IntPtr.Zero)
                    {
                        Lpnr.LPNRProgram.LPNR_SetWinMsg(Lpnr_Handle[0], this.Handle, MY_MSG_BEGIN);//消息接收窗口
                    }
                    if (Common.ConfigHelper.GetConnectionStringConfig("hasH264") == "yes")
                    {
                        if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "0")
                        {
                            H264_Handle[0] = H264.H264Decoder.H264DEC_Init(CameraIP[0], 1);

                            if (H264_Handle[0] != IntPtr.Zero)
                            {
                                H264.H264Decoder.H264DEC_SetWinMsg(H264_Handle[0], this.Handle, MY_MSG_BEGIN_H264);//消息接收窗口
                                vedioBit[0] = true;
                            }
                        }
                        //采用最新的video动态库
                        else if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "1")
                        {
                            H264_Handle[0] = RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Create(CameraIP[0], 1);

                            if (H264_Handle[0] != IntPtr.Zero)
                            {
                                FlashLog.FlashLogger.Info("VIDEO_Create 初始化成功 " + H264_Handle[0].ToString());

                                if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_SetRenderWindow(H264_Handle[0], this.pictureBox_VideoNo1.Handle)) //消息接收窗口
                                {
                                    if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Start(H264_Handle[0]))
                                    {
                                        FlashLog.FlashLogger.Info("VIDEO_Start 启动成功");
                                        vedioBit[0] = true;
                                    }
                                }

                            }
                        }
                    }
                }
                else
                {
                    UIMessageBox.Show("IP地址格式错误", "IP检查出错", UIStyle.Red, UIMessageBoxButtons.OK, true, true);
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("初始化抓拍机失败" + ex.Message.ToString());
            }
        }


        /// <summary>
        /// 德亚初始化抓拍机
        /// </summary>
        public void LPNR_Init_2()
        {
            try
            {
                CameraIP[1] = uiComboBox_LpnrIpNo2.Text.Trim();
                IPAddress ip;
                if (IPAddress.TryParse(CameraIP[1], out ip))
                {
                    Lpnr_Handle[1] = Lpnr.LPNRProgram.LPNR_Init(CameraIP[1]);//初始化LPNRTool摄像机句柄

                    if (Lpnr_Handle[1] != null)
                    {
                        Lpnr.LPNRProgram.LPNR_SetWinMsg(Lpnr_Handle[1], this.Handle, MY_MSG_BEGIN_2);//消息接收窗口
                        //Creat_CameraThread_Function();//回调函数
                    }
                    if (Common.ConfigHelper.GetConnectionStringConfig("hasH264") == "yes")
                    {
                        if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "0")
                        {
                            H264_Handle[1] = H264.H264Decoder.H264DEC_Init(CameraIP[1], 1);

                            if (H264_Handle[1] != null)
                            {
                                H264.H264Decoder.H264DEC_SetWinMsg(H264_Handle[1], this.Handle, MY_MSG_BEGIN_H264_2);//消息接收窗口
                                vedioBit[1] = true;
                            }
                        }
                        //采用最新的vedio动态库
                        else if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "1")
                        {
                            H264_Handle[1] = RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Create(CameraIP[1], 1);

                            if (H264_Handle[1] != IntPtr.Zero)
                            {
                                FlashLog.FlashLogger.Info("VIDEO_Create2 初始化成功 " + H264_Handle[1].ToString());

                                if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_SetRenderWindow(H264_Handle[1], this.pictureBox_VideoNo2.Handle)) 
                                {
                                    if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Start(H264_Handle[1]))
                                    {
                                        FlashLog.FlashLogger.Info("VIDEO_Start2 启动成功");
                                        vedioBit[1] = true;
                                    }
                                }
                            }

                        }
                    }
                }
                else
                {
                    UIMessageBox.Show("IP地址格式错误", "IP检查出错", UIStyle.Red, UIMessageBoxButtons.OK, true, true);
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("初始化抓拍机失败" + ex.Message.ToString());
            }
        }


        public bool[] online = { false, false };
        public bool[] IsIdle = { false, false };

        /// <summary>
        /// 判断摄像机是否在线
        /// </summary>
        public void judgeonline()
        {
            online[0] = Lpnr.LPNRProgram.LPNR_IsOnline(Lpnr_Handle[0]);
            IsIdle[0] = Lpnr.LPNRProgram.LPNR_IsIdle(Lpnr_Handle[0]);

            this.pictureBox_VideoNo1.Visible = true;

            this.pictureBox_SnapImage1.Visible = true;

            try
            {
                _isresetlinkbit[0] = false;
                while (_isresetlinkbit[0] == false)
                {
                    if (online[0] == true)
                    {
                        getMachineIp();//获取车牌ip

                        Trace.WriteLogFile("事件编号1：LPNR连线");
                        Trace.WriteLogFile("LPNRTool online is " + online[0]);
                        Trace.WriteLogFile("抓拍机是否在识别中" + IsIdle[0]);
                        Link_InitButton.Enabled = false;
                        Close_OffButton.Enabled = true;
                        Trace.WriteLogFile("摄像机初始化完成！");

                        //if (judgeInIplist(CameraIP[0]) == false)
                        //{
                        //    Trace.writeIpList(CameraIP[0]);//将ip地址写入CamreaList
                        //}
                        _isresetlinkbit[0] = false;
                        break;
                    }
                    else
                    {
                        Lpnr_Handle[0] = Lpnr.LPNRProgram.LPNR_Init(CameraIP[0]);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        public void judgeonline_1()
        {
            online[1] = Lpnr.LPNRProgram.LPNR_IsOnline(Lpnr_Handle[1]);
            IsIdle[1] = Lpnr.LPNRProgram.LPNR_IsIdle(Lpnr_Handle[1]);

            this.pictureBox_VideoNo2.Visible = true;
            this.pictureBox_SnapImage2.Visible = true;

            try
            {
                _isresetlinkbit[1] = false;
                while (_isresetlinkbit[1] == false)
                {
                    if (online[1] == true)
                    {
                        getMachineIp_2();//获取车牌ip

                        Trace.WriteLogFile("事件编号1：LPNR连线");
                        Trace.WriteLogFile("LPNRTool online is " + online[1]);
                        Trace.WriteLogFile("抓拍机是否在识别中" + IsIdle[1]);

                        Link_Init_2Button.Enabled = false;
                        Close_Off_2Button.Enabled = true;
                        Trace.WriteLogFile("摄像机初始化完成！");

                        //if (judgeInIplist(CameraIP[1]) == false)
                        //{
                        //    Trace.writeIpList(CameraIP[1]);//将ip地址写入CamreaList
                        //}
                        _isresetlinkbit[1] = false;
                        break;
                    }
                    else
                    {
                        Lpnr_Handle[1] = Lpnr.LPNRProgram.LPNR_Init(CameraIP[1]);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }

        public bool[] _isresetlinkbit = { false, false }; //是否重连

        /// <summary>
        /// DataGridViewAdd显示过车数据
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="dt"></param>
        public void DataGridViewAdd(Common.DataObject obj, Sunny.UI.UIDataGridView dt)
        {
            try
            {
                int index = dt.Rows.Add();

                dt.Rows[index].Cells[0].Value = obj.serialNumber;
                dt.Rows[index].Cells[1].Value = obj.triggerTime;
                dt.Rows[index].Cells[2].Value = obj.plateNo;
                dt.Rows[index].Cells[3].Value = obj.vehicleType;

                if (WelcomeLedIphwnd != IntPtr.Zero)
                {
                    Led.TFIProgram.TFI_SendLine(WelcomeLedIphwnd, Led.TFIInit.FirstLineNum, Led.TFIInit.ColorYellow, Led.TFIInit.RollModeCenter, Led.TFIInit.RollSpeedThree, obj.plateNo);
                    Led.TFIProgram.TFI_SendLine(WelcomeLedIphwnd, Led.TFIInit.SencondLineNum, Led.TFIInit.ColorYellow, Led.TFIInit.RollModeCenter, Led.TFIInit.RollSpeedThree, obj.vehicleType);
                }

                // 滚动条滚动到最后
                if (dt.Rows.Count >= 1)
                {
                    dt.FirstDisplayedScrollingRowIndex = dt.Rows.Count - 1;
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常DataGridViewAdd " + ex.ToString());
            }
        }

        public int Vehiclecount = 0;
        public int Vehiclecount1 = 0;
        public int i = 1;

        public bool GetVedio = false;
        public Thread ShowVedioThread = null;

        //拦截并处理系统消息和自定义消息
        protected override void WndProc(ref Message m)
        {
            try
            {
                if (m.Msg == MY_MSG_BEGIN)
                {
                    switch (int.Parse(m.LParam.ToString()))
                    {
                        case 1:
                            My_MSG_HANDLE[0] = 1;
                            CameraLabel = Lpnr.LPNRProgram.LPNR_GetCameraLabel(Lpnr_Handle[0]);

                            Lpnr.LPNRProgram.LPNR_EnableLiveFrame(Lpnr_Handle[0], 1);//2017/12/25 添加使能实时视频才能收到
                            judgeonline();//判断是否online

                            if (Lpnr.LPNRProgram.LPNR_COM_init(Lpnr_Handle[0], 9600))
                            {
                                if (Lpnr.LPNRProgram.LPNR_COM_aync(Lpnr_Handle[0], true))
                                {
                                    Trace.WriteLogFile("串口透传初始化完成");
                                }
                            }
                            else
                            {
                                Trace.WriteLogFile("串口透传初始化失败");
                            }

                            break;
                        case 2: My_MSG_HANDLE[0] = 2; Trace.WriteLogFile("事件编号2：LPNR离线"); GetVedio = false; break;
                        case 3: My_MSG_HANDLE[0] = 3; Trace.WriteLogFile("事件编号3：开始进行识别处理"); break;
                        case 4:
                            My_MSG_HANDLE[0] = 4;
                            Trace.WriteLogFile("事件编号4：识别处理结束可以获取结果。（上位机要等收到事件编号4后才可以去获取车牌信息和图片）");

                            dataInfoNo[0].plateNo = GetPlateFunction(Lpnr_Handle[0], this.PlateText, this.uiTextBox_plateColorNo1,ref dataInfoNo[0]);//获取车牌号 
                            dataInfoNo[0].serialNumber = dataInfoNo[0].serialNumber + 1;
                            dataInfoNo[0].triggerTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                            getPlateAttribute(Lpnr_Handle[0], this.confidenceText);//获取额外信息

                            getplatecolorFunction(Lpnr_Handle[0], this.ColorpictureBox);//获取彩色图
                            getplatBinaryFunction(Lpnr_Handle[0], this.BinarypictureBox);//获取二值化
                                                                                         //GetTiming();//获取处理时间

                            showinfo(Lpnr_Handle[0], this.uiTextBox_InforNo1, this.confidenceText);//显示处理时间

                            //getimageFunction(Lpnr_Handle[0],12, 320,this.pictureBox_SnapImage1);//获取抓拍图片
                            //getimageFunction(Lpnr_Handle[0],this.pictureBox_SnapImage1.Location.X, this.pictureBox_SnapImage1.Location.Y,this.pictureBox_SnapImage1);//获取抓拍图片
                            
                            dataInfoNo[0].picfile = getimageFunction(
                                Lpnr_Handle[0],
                                 this.pictureBox_SnapImage1.Width,
                                  this.pictureBox_SnapImage1.Height,
                                this.pictureBox_SnapImage1.Location.X,
                                this.pictureBox_SnapImage1.Location.Y,
                                this.pictureBox_SnapImage1);//获取抓拍图片

                            _isreleasedata = Lpnr.LPNRProgram.LPNR_ReleaseData(Lpnr_Handle[0]);//释放当前识别结果动态分配的数据

                            //查询后台获取车辆类型
                            dataInfoNo[0].vehicleType = GetVehicleType(this.uiTextBox_vehicleType, dataInfoNo[0].plateNo);
                            DataGridViewAdd(dataInfoNo[0], this.uiDataGridView_laneNo1);


                            //连云港矿业接口测试
                            string ulid = Utils.DataChage.GetGuid().Replace("-", "");
                            Common.Lyg_SendData.Lyg_ParkingDataInfo parkinfo = Common.Lyg_SendData.ParkInfo_Init(0);//初始化

                            parkinfo.txId = ulid;
                            parkinfo.plateColor = dataInfoNo[0].plateColor;
                            parkinfo.plate = dataInfoNo[0].plateNo;
                            switch (Common.ConfigHelper.GetConnectionStringConfig("LaneType_1"))
                            {
                                case "0": parkinfo.entryTime = dataInfoNo[0].triggerTime; break;
                                case "1": parkinfo.exitTime = dataInfoNo[0].triggerTime; break;
                                default: break;
                            }
                            parkinfo.image1 = Utils.DataChage.ImgToBase64String(dataInfoNo[0].picfile);
                            SendParkData(parkinfo);//更新队列数据


                            break;
                        case 5:
                            My_MSG_HANDLE[0] = 5;

                            //GetVedio = true;

                            if (Lpnr_Handle[0] != IntPtr.Zero && (Common.ConfigHelper.GetConnectionStringConfig("hasH264") == "no") && Common.ConfigHelper.GetConnectionStringConfig("haslpnrrtsp") == "no")
                            {
                                GetLiveVideo();
                            }

                            break;
                        case 6: My_MSG_HANDLE[0] = 6; Trace.WriteLogFile("事件编号6：车辆进入虚拟线圈检测区"); break;
                        case 7: My_MSG_HANDLE[0] = 7; Trace.WriteLogFile("事件编号7：车辆离开虚拟线圈检测区"); break;
                        case 8: My_MSG_HANDLE[0] = 8; Trace.WriteLogFile("事件编号8：扩展DI点状态有变化（一体机才有扩展DI）"); break;
                        default:
                            break;
                    };
                }

                if (m.Msg == MY_MSG_BEGIN_2)
                {
                    switch (int.Parse(m.LParam.ToString()))
                    {
                        case 1:
                            My_MSG_HANDLE[1] = 1;
                            CameraLabel = Lpnr.LPNRProgram.LPNR_GetCameraLabel(Lpnr_Handle[1]);

                            Lpnr.LPNRProgram.LPNR_EnableLiveFrame(Lpnr_Handle[1], 1);//2017/12/25 添加使能实时视频才能收到
                            judgeonline_1();//判断是否online

                            if (Lpnr.LPNRProgram.LPNR_COM_init(Lpnr_Handle[1], 9600))
                            {
                                if (Lpnr.LPNRProgram.LPNR_COM_aync(Lpnr_Handle[1], true))
                                {
                                    Trace.WriteLogFile("串口透传初始化完成");
                                }
                            }
                            else
                            {
                                Trace.WriteLogFile("串口透传初始化失败");
                            }

                            break;
                        case 2: My_MSG_HANDLE[1] = 2; Trace.WriteLogFile("事件编号2：LPNR离线"); GetVedio = false; break;
                        case 3: My_MSG_HANDLE[1] = 3; Trace.WriteLogFile("事件编号3：开始进行识别处理"); break;
                        case 4:
                            My_MSG_HANDLE[1] = 4;
                            Trace.WriteLogFile("事件编号4：识别处理结束可以获取结果。（上位机要等收到事件编号4后才可以去获取车牌信息和图片）");

                            dataInfoNo[1].plateNo = GetPlateFunction(Lpnr_Handle[1], this.PlateText_2, this.uiTextBox_plateColorNo2, ref dataInfoNo[1]);//获取车牌号 
                            dataInfoNo[1].serialNumber = dataInfoNo[1].serialNumber + 1;
                            dataInfoNo[1].triggerTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                            getPlateAttribute(Lpnr_Handle[1], this.confidenceText_2);//获取额外信息
                            getplatecolorFunction(Lpnr_Handle[1], this.ColorpictureBox_2);//获取彩色图
                            getplatBinaryFunction(Lpnr_Handle[1], this.BinarypictureBox_2);//获取二值化

                            //GetTiming();//获取处理时间
                            showinfo(Lpnr_Handle[1], this.uiTextBox_InforNo2, this.confidenceText_2);//显示处理时间
                                                                                                     //getimageFunction(Lpnr_Handle[1], 572, 320, this.pictureBox_SnapImage2);

                            dataInfoNo[1].picfile= getimageFunction(
                                Lpnr_Handle[1],
                                 this.pictureBox_SnapImage2.Width,
                                  this.pictureBox_SnapImage2.Height,
                                this.pictureBox_SnapImage2.Location.X,
                                this.pictureBox_SnapImage2.Location.Y,
                                this.pictureBox_SnapImage2);


                            _isreleasedata = Lpnr.LPNRProgram.LPNR_ReleaseData(Lpnr_Handle[1]);//释放当前识别结果动态分配的数据

                            //查询后台返回车辆类型
                            dataInfoNo[1].vehicleType = GetVehicleType(this.uiTextBox_vehicleType2, dataInfoNo[1].plateNo);
                            DataGridViewAdd(dataInfoNo[1], this.uiDataGridView_laneNo2);


                            //连云港矿业接口测试
                            string ulid = Utils.DataChage.GetGuid().Replace("-", "");
                            Common.Lyg_SendData.Lyg_ParkingDataInfo parkinfo = Common.Lyg_SendData.ParkInfo_Init(1);//初始化

                            parkinfo.txId = ulid;
                            parkinfo.plateColor = dataInfoNo[1].plateColor;
                            parkinfo.plate = dataInfoNo[1].plateNo;

                            switch (Common.ConfigHelper.GetConnectionStringConfig("LaneType_2"))
                            {
                                case "0": parkinfo.entryTime = dataInfoNo[1].triggerTime; break;
                                case "1": parkinfo.exitTime = dataInfoNo[1].triggerTime; break;
                                default:break;
                            }
                            parkinfo.image1 = Utils.DataChage.ImgToBase64String(dataInfoNo[1].picfile);
                            SendParkData(parkinfo);//更新队列数据

                            //if (Vehiclecount != 0)
                            //    MessageBox.Show(Vehiclecount.ToString(), "123", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            break;
                        case 5:
                            My_MSG_HANDLE[1] = 5;

                            //GetVedio = true;
                            if (Lpnr_Handle[1] != IntPtr.Zero && (Common.ConfigHelper.GetConnectionStringConfig("hasH264") == "no") && Common.ConfigHelper.GetConnectionStringConfig("haslpnrrtsp") == "no")
                            {
                                GetLiveVideo_2();
                            }

                            break;
                        case 6: My_MSG_HANDLE[1] = 6; Trace.WriteLogFile("事件编号6：车辆进入虚拟线圈检测区"); break;
                        case 7: My_MSG_HANDLE[1] = 7; Trace.WriteLogFile("事件编号7：车辆离开虚拟线圈检测区"); break;
                        case 8: My_MSG_HANDLE[1] = 8; Trace.WriteLogFile("事件编号8：扩展DI点状态有变化（一体机才有扩展DI）"); break;
                        default:
                            break;
                    };
                }

                if (m.Msg == MY_MSG_BEGIN_H264)
                {
                    switch (int.Parse(m.LParam.ToString()))
                    {
                        case 1:
                            FlashLog.FlashLogger.Info("识别机连线");
                            break;
                        case 2:
                            FlashLog.FlashLogger.Info("识别机离线");
                            break;
                        case 3:
                            //FlashLog.FlashLogger.Info("实时图像更新");
                            int size = (int)H264.H264Decoder.H264DEC_GetFrameSize(H264_Handle[0]);
                            byte[] my_frame_buffer;

                            if (H264_buff[0] != size)
                            {
                                H264_buff[0] = size;
                            }
                            my_frame_buffer = new byte[size];

                            if (H264_Handle[0] != null && my_frame_buffer != null)
                            {
                                H264.H264Decoder.H264DEC_GetFrameImage(H264_Handle[0], my_frame_buffer);
                            }

                            showVideoToPicture(this.pictureBox_VideoNo1.Width,
                                    this.pictureBox_VideoNo1.Height,
                                    this.pictureBox_VideoNo1.Location.X,
                                    this.pictureBox_VideoNo1.Location.Y,
                                    this.pictureBox_VideoNo1,
                                    my_frame_buffer);

                            break;
                        case 5:
                            FlashLog.FlashLogger.Info("H264帧到了");
                            break;
                        default:
                            break;
                    }


                }
                if (m.Msg == MY_MSG_BEGIN_H264_2)
                {
                    switch (int.Parse(m.LParam.ToString()))
                    {
                        case 1:
                            FlashLog.FlashLogger.Info("识别机连线");
                            break;
                        case 2:
                            FlashLog.FlashLogger.Info("识别机离线");
                            break;
                        case 3:
                            //FlashLog.FlashLogger.Info("实时图像更新");

                            int size = (int)H264.H264Decoder.H264DEC_GetFrameSize(H264_Handle[1]);
                            byte[] my_frame_buffer;

                            if (H264_buff[1] != size)
                            {
                                H264_buff[1] = size;
                            }
                            my_frame_buffer = new byte[size];

                            if (H264_Handle[1] != null && my_frame_buffer != null)
                            {
                                H264.H264Decoder.H264DEC_GetFrameImage(H264_Handle[1], my_frame_buffer);
                            }

                            showVideoToPicture(this.pictureBox_VideoNo2.Width,
                                    this.pictureBox_VideoNo2.Height,
                                    this.pictureBox_VideoNo2.Location.X,
                                    this.pictureBox_VideoNo2.Location.Y,
                                    this.pictureBox_VideoNo2,
                                    my_frame_buffer);

                            break;
                        case 5:
                            FlashLog.FlashLogger.Info("H264帧到了");
                            break;
                        default:
                            break;
                    }
                }


                else if (m.Msg == MY_MSG_END)
                {
                    FlashLog.FlashLogger.Debug("类Demo for循环结束.");
                }

                base.WndProc(ref m);
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("Exception WndProc " + ex.ToString());
            }
        }



        /// <summary>
        /// 获取抓拍机IP号
        /// </summary>
        public void getMachineIp()
        {
            byte[] ip = new byte[CameraIP[0].Length];
            Lpnr.LPNRProgram.LPNR_GetMachineIP(Lpnr_Handle[0], ip);
            GetManchineIPAddress = Encoding.Default.GetString(ip, 0, ip.Length);
            Trace.WriteLogFile("获取到设备IP" + GetManchineIPAddress);
        }

        /// <summary>
        /// 获取抓拍机IP号
        /// </summary>
        public void getMachineIp_2()
        {
            byte[] ip = new byte[CameraIP[1].Length];
            Lpnr.LPNRProgram.LPNR_GetMachineIP(Lpnr_Handle[1], ip);
            GetManchineIPAddress = Encoding.Default.GetString(ip, 0, ip.Length);
            Trace.WriteLogFile("获取到设备IP" + GetManchineIPAddress);
        }

        /// <summary>
        /// 显示处理时间 车牌额外信息
        /// </summary>
        public void showinfo(IntPtr h, Sunny.UI.UITextBox pb, UITextBox confidence)
        {
            string a = GetTiming(h);
            string b = getPlateAttribute(h, confidence);
            string c = a + b;
            pb.ForeColor = Color.Blue;
            pb.Text = c;
        }

        /// <summary>
        /// 获取处理时间
        /// </summary>
        public string GetTiming(IntPtr h)
        {
            int processtime = 0;
            int handletime = 0;
            Lpnr.LPNRProgram.LPNR_GetTiming(h, ref processtime, ref handletime);
            Trace.WriteLogFile("总过程时间:" + processtime + "ms" + "  " + "总处理时间:" + handletime + "ms");

            return "总过程时间:" + processtime + "ms" + "\r\n" + "总处理时间:" + handletime + "ms" + "\r\n";
        }

        /// <summary>
        /// 获取车牌额外的信息
        /// </summary>
        public string getPlateAttribute(IntPtr h, UITextBox tx)
        {
            byte[] plateattr = new byte[8];
            Lpnr.LPNRProgram.LPNR_GetPlateAttribute(h, plateattr);
            string confidencestr = plateattr[0].ToString();//可信度
            string headortailstr = plateattr[1].ToString();//车头或是车尾的车牌 1：车头，0xff 车尾，0 未知
            string carcolorstr = plateattr[2].ToString();//车身颜色码
            string carspeedstr = plateattr[3].ToString();//车速
            string triggersourcestr = plateattr[4].ToString();//触发源 (0：图片返送，1：上位机触发，2：线圈触发，3：定时触发，4：虚拟线圈触发，5：超速触发)

            string platedirection = "";
            string speed = "";
            string trigger = "";

            if (confidencestr != "0")
            {
                tx.Text = confidencestr + "%";
            }
            else
            {
                tx.Text = "";
            }

            if (carspeedstr != "0")
            {
                speed = carspeedstr;
            }
            else
            {
                speed = "";
            }
            switch (headortailstr)
            {
                case "1": platedirection = "车头"; break;
                case "0xff": platedirection = "车尾"; break;
                case "0": platedirection = "未知"; break;
                default: break;
            }

            switch (triggersourcestr)
            {
                case "0": trigger = "图片返送"; break;
                case "1": trigger = "上位机触发"; break;
                case "2": trigger = "线圈触发"; break;
                case "3": trigger = "定时触发"; break;
                //case "4": trigger = "虚拟线圈触发"; break;
                case "4": trigger = "视频触发"; break;
                case "5": trigger = "超速触发"; break;
                default: break;
            }
            Trace.WriteLogFile("触发方式:" + trigger + "\r\n");
            return "触发方式:" + trigger + "\r\n" + "车牌位置:" + platedirection;
        }

        /// <summary>
        /// 获取车牌号方法
        /// </summary>
        public void GetPlateFunction()
        {
            try
            {
                byte[] plante = new byte[12];

                Lpnr.LPNRProgram.LPNR_Lock(Lpnr_Handle[0]);//上锁
                Lpnr.LPNRProgram.LPNR_GetPlateNumber(Lpnr_Handle[0], plante);

                planetAll = Encoding.Default.GetString(plante, 0, plante.Length).Trim(('\0'));
                Trace.WriteLogFile("车牌识别结果:" + "-----------------" + planetAll);
                if (planetAll != string.Empty)
                {
                    showplatehandle(planetAll);//处理车牌至textbox显示
                    Lpnr.LPNRProgram.LPNR_Unlock(Lpnr_Handle[0]);//解锁
                }
                else
                {
                    Lpnr.LPNRProgram.LPNR_Unlock(Lpnr_Handle[0]);//解锁
                    Trace.WriteLogFile("车牌识别结果为null" + "-----------------");
                }
                _isgetplate = true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }





        /// <summary>
        /// 获取车牌号方法 带参
        /// </summary>
        public string GetPlateFunction(IntPtr h, Sunny.UI.UITextBox tb, Sunny.UI.UITextBox tbColor, ref Common.DataObject dataInfoNo)
        {
            try
            {
                byte[] plante = new byte[12];

                Lpnr.LPNRProgram.LPNR_Lock(h);//上锁
                Lpnr.LPNRProgram.LPNR_GetPlateNumber(h, plante);
                Lpnr.LPNRProgram.LPNR_Unlock(h);//解锁

                planetAll = Encoding.Default.GetString(plante, 0, plante.Length).Trim(('\0'));
                Trace.WriteLogFile("车牌识别结果:" + "-----------------" + planetAll);
                if (planetAll != string.Empty)
                {
                    //showplatehandle(planetAll);//处理车牌至textbox显示
                    showplatehandle(planetAll, tb, tbColor, ref dataInfoNo);


                    //测试传化网络控制器功能 识别到车牌发送抬杆命令
                    /*
                    if (uiCheckBox_NetCtrl.Checked == true & lanetype == "2")
                    {
                        string str = LaneIp[0] + "|0";
                        tcpsend(str);s
                        MethodInvoker mi = new MethodInvoker(ShowProcessBar);
                        this.BeginInvoke(mi);
                        Thread.Sleep(50);
                    }
                    */
                    return planetAll;
                }
                else
                {
                    FlashLog.FlashLogger.Info("车牌识别结果为null" + "-----------------");
                }
                _isgetplate = true;

                return null;
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("Exception GetPlateFunction " + ex.Message);
                return null;
            }
        }


        public delegate string MethodCaller(Sunny.UI.UITextBox tb, string inOuturl, string guid, string ulid, string plate, string voucher, string triggerTime);//定义代理

        public string GetVehicleType(Sunny.UI.UITextBox tb, string plate)
        {
            try
            {
                if (Common.ConfigHelper.GetConnectionStringConfig("hasRequest") == "yes")
                {
                    //请求后台判断车辆类型
                    string guid = Utils.DataChage.GetGuid().Replace("-", "");
                    string ulid = "";
                    string inOuturl = Common.ConfigHelper.GetConnectionStringConfig("DyPostUrl");
                    switch (tb.Name)
                    {
                        case "uiTextBox_vehicleType":
                            ulid = Common.ConfigHelper.GetConnectionStringConfig("ULID_1");

                            if (Common.ConfigHelper.GetConnectionStringConfig("LaneType_1") == "0")
                            {
                                inOuturl += "AskInParkingCar";

                            }
                            else if (Common.ConfigHelper.GetConnectionStringConfig("LaneType_1") == "1")
                            {
                                inOuturl += "AskOutParkingCar";
                            }
                            break;
                        case "uiTextBox_vehicleType2":
                            ulid = Common.ConfigHelper.GetConnectionStringConfig("ULID_2");

                            if (Common.ConfigHelper.GetConnectionStringConfig("LaneType_2") == "0")
                            {
                                inOuturl += "AskInParkingCar";

                            }
                            else if (Common.ConfigHelper.GetConnectionStringConfig("LaneType_2") == "1")
                            {
                                inOuturl += "AskOutParkingCar";
                            }
                            break;
                        default: break;
                    }

                    //请求后台 显示车辆类型 
                    /*
                    requestThreadClass myThread = new requestThreadClass(tb,inOuturl,guid, ulid, planetAll, planetAll, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    Thread requestThread = new Thread(myThread.requestThreadMain);
                    ThreadList.Add(requestThread);
                    requestThread.Start();
                    requestThread.IsBackground = true;
                    */

                    MethodCaller mc = new MethodCaller(requestThreadMain);
                    IAsyncResult result = mc.BeginInvoke(tb, inOuturl, guid, ulid, plate, plate, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), null, null);
                    string myname = mc.EndInvoke(result);//用于接收返回值

                    FlashLog.FlashLogger.Info("查询后台线程返回值:" + myname);
                    tb.Text = myname;

                    vehicleType = plate+" "+ myname;
                    MethodInvoker mi = new MethodInvoker(ShowNoteTitleBar);//该委托可以执行托管代码中声明为void且不接受任何参数的任何方法
                    this.BeginInvoke(mi);

                    return myname;
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常GetVehicleType " + ex.ToString());
                return null;
            }
            return null;
        }



        public string requestThreadMain(Sunny.UI.UITextBox tb, string inOuturl, string guid, string ulid, string plate, string voucher, string triggerTime)
        {
            Common.RequestObject req = new Common.RequestObject();

            req.postUrl = inOuturl;
            req.Guid = guid;
            req.Ulid = ulid;
            req.Plate = plate;
            req.Voucher = voucher;
            req.TriggerTime = triggerTime;

            try
            {
                Encoding encoding = Encoding.GetEncoding("utf-8");

                //json格式参数
                StringBuilder data = new StringBuilder();
                data.Append("{");
                data.Append("\"Guid\":\"" + req.Guid + "\",");
                data.Append("\"Ulid\":\"" + req.Ulid + "\",");
                data.Append("\"Plate\":\"" + req.Plate + "\",");
                data.Append("\"Voucher\":\"" + req.Voucher + "\",");
                data.Append("\"VoucherType\":\"" + req.VoucherType + "\",");
                data.Append("\"TriggerTime\":\"" + req.TriggerTime + "\"");
                data.Append("}");

                string param = Utils.DataChage.ConvertJsonString(data.ToString());

                FlashLog.FlashLogger.Info("后台请求postUrl：" + req.postUrl);

                HttpWebResponse response = http.HTTPPost.CreatePostHttpResponseJson(req.postUrl, param, encoding);

                if (response != null)
                {
                    Stream stream = response.GetResponseStream();   //获取响应的字符串流
                    StreamReader sr = new StreamReader(stream);     //创建一个stream读取流
                    string recHtml = sr.ReadToEnd();                //从头读到尾，放到字符串html
                    FlashLog.FlashLogger.Info("后台返回值:  " + recHtml + "\r\n");
                    if (recHtml != null)
                    {
                        string re = handleRequestJson(tb, recHtml);
                        FlashLog.FlashLogger.Info("json解析 车辆类型：" + re);

                      

                        return re;
                    }
                }
                else
                {
                    FlashLog.FlashLogger.Debug("后台请求失败");
                    return null;
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("requestThreadMain " + ex.Message.ToString() + "\r\n");
                return null;
            }
            return null;
        }


      







    /// <summary>
    /// 处理后台返回的json
    /// </summary>
    /// <param name="rec"></param>
    public string handleRequestJson(Sunny.UI.UITextBox tb, string rec)
        {
            try
            {
                AskInParkingObject askin = JsonConvert.DeserializeObject<AskInParkingObject>(rec);
                string vehicletype = askin.VehicleType;
                string _AllowPass = askin.AllowPass;

                return vehicletype;
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常handleRequestJson " + ex.ToString());
                return "";
            }

        }

        /// <summary>
        /// 连云港矿业post参数 车牌数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="txId"></param>
        /// <param name="parkCode"></param>
        /// <param name="parkName"></param>
        /// <param name="laneCode"></param>
        /// <param name="laneName"></param>
        /// <param name="plate"></param>
        /// <param name="plateColor"></param>
        /// <param name="triggerTime"></param>
        /// <param name="remarks"></param>
        /// <returns></returns>
        public static bool postThreadMain(Common.Lyg_SendData.Lyg_ParkingDataInfo obj)
        {

          string  postUrl = obj.url + "/RecordTrafficWithImage";
            try
            {
                Encoding encoding = Encoding.GetEncoding("utf-8");

                IDictionary<string, string> parameters = new Dictionary<string, string>();

                parameters.Add("txId", obj.txId);
                parameters.Add("parkCode", obj.parkCode);
                parameters.Add("parkName", obj.parkName);
                parameters.Add("laneCode", obj.laneCode);
                parameters.Add("laneName", obj.laneName);
                parameters.Add("plate", obj.plate);
                parameters.Add("plateColor", obj.plateColor);
                parameters.Add("entryTime", obj.entryTime);
                parameters.Add("remarks", obj.remarks);
                parameters.Add("image1", obj.image1);
                parameters.Add("exitTime", obj.exitTime);

                FlashLog.FlashLogger.Info("postThreadMain 后台请求postUrl：" + postUrl);
                FlashLog.FlashLogger.Info("postThreadMain 参数：{" + "\n"
                   + "txId: " + obj.txId +"\n"
                    + "parkCode: " + obj.parkCode + "\n"
                    + "parkName: " + obj.parkName + "\n"
                    + "laneCode: " + obj.laneCode + "\n"
                    + "laneName: " + obj.laneName + "\n"
                    + "plate: " + obj.plate+"\n"
                    + "plateColor: " + obj.plateColor + "\n"
                    + "entryTime: " + obj.entryTime + "\n"
                    + "remarks: " + obj.remarks + "\n"
                    + "exitTime: " + obj.exitTime +"}"+ "\n");
                string rec = http.HTTPPost.HttpPostMultipartFormData(postUrl, parameters, "POST", "UTF-8", -1);

                return true;
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("postThreadMain " + ex.Message.ToString() + "\r\n");
                return false;
            }
          
        }


        /// <summary>
        /// 弹窗显示对应字符串
        /// </summary>
        private void ShowNoteTitleBar()
        {
            UINotifierHelper.ShowNotifier(vehicleType, UINotifierType.OK, UILocalize.InfoTitle, false, 10000);
        }



        //弹窗
        private void ShowProcessBar()
        {
            UINotifierHelper.ShowNotifier("发送抬杆命令成功", UINotifierType.OK, UILocalize.WarningTitle, false, 2000);
        }


        public void showplatehandle(string info)
        {
            string plantecolor = info.Substring(0, 1);
            //string planetNo = info.Remove(0, 1);
            string planetNo = info;
            Trace.WriteLogFile("解析后车牌颜色：" + plantecolor + "  " + "车牌：" + planetNo);


            if (plantecolor != " ")
            {
                Recognition_success_rate = Recognition_success_rate + 1;
                Trace.WriteLogFile("识别成功数量：" + Recognition_success_rate);
                Trace.WriteLogFile("识别成功率：" + Math.Round(((decimal)Recognition_success_rate / Recognition_total) * 100, 2) + "%");
            }

            switch (plantecolor)
            {
                case "黄":
                    this.PlateText.Text = planetNo;
                    this.uiTextBox_plateColorNo1.Text = "黄";
                    this.PlateText.BackColor = Color.Yellow;
                    this.PlateText.ForeColor = Color.Black;
                    //this.PlateText.TextAlign = HorizontalAlignment.Center;
                    break;
                case "蓝":
                    this.PlateText.BackColor = Color.Blue;
                    this.uiTextBox_plateColorNo1.Text = "蓝";
                    this.PlateText.ForeColor = Color.White;
                    this.PlateText.Text = planetNo;
                    break;
                case "白":
                    this.PlateText.BackColor = Color.White;
                    this.uiTextBox_plateColorNo1.Text = "白";
                    this.PlateText.ForeColor = Color.Black;
                    this.PlateText.Text = planetNo;
                    break;
                case "绿":
                    this.PlateText.BackColor = Color.PaleGreen;
                    this.uiTextBox_plateColorNo1.Text = "绿";
                    this.PlateText.ForeColor = Color.Black;
                    this.PlateText.Text = planetNo;
                    break;
                case "黑":
                    this.PlateText.BackColor = Color.Black;
                    this.uiTextBox_plateColorNo1.Text = "黑";
                    this.PlateText.ForeColor = Color.White;
                    this.PlateText.Text = planetNo;
                    break;
                default:
                    this.PlateText.BackColor = Color.Red;
                    this.uiTextBox_plateColorNo1.Text = "";
                    this.PlateText.ForeColor = Color.White;
                    this.PlateText.Text = "无车牌";
                    break;
            }
        }


        /// <summary>
        /// 处理车牌识别
        /// </summary>
        /// <param name="info"></param>
        /// <param name="tb"></param>
        public void showplatehandle(string info, Sunny.UI.UITextBox tb, Sunny.UI.UITextBox tbColor, ref Common.DataObject dataInfoNo)
        {
            string plantecolor = info.Substring(0, 1);
            //string planetNo = info.Remove(0, 1);
            string planetNo = info;
            FlashLog.FlashLogger.Info("解析后车牌颜色：" + plantecolor + "  " + "车牌：" + planetNo);

            dataInfoNo.plateColor = plantecolor;
            switch (plantecolor)
            {
                case "黄":
                    tb.Text = planetNo;
                    //tb.BackColor = UIColor.LightOrange;
                    //tb.ForeColor = UIColor.Black;
                    tbColor.Text = "黄";
                    //this.PlateText.TextAlign = HorizontalAlignment.Center;
                    break;
                case "蓝":
                    tb.BackColor = UIColor.Blue;
                    tbColor.Text = "蓝";
                    //tb.ForeColor = UIColor.White;
                    tb.Text = planetNo;
                    break;
                case "白":
                    tbColor.Text = "白";
                    //tb.BackColor = UIColor.White;
                    //tb.ForeColor = UIColor.Black;
                    tb.Text = planetNo;
                    break;
                case "绿":
                    tbColor.Text = "绿";
                    //tb.BackColor = Color.PaleGreen;
                    //tb.ForeColor = Color.Black;
                    tb.Text = planetNo;
                    break;
                case "秋":
                    tbColor.Text = "秋";
                    //tb.BackColor = Color.Peru;
                    //tb.ForeColor = Color.Black;
                    tb.Text = planetNo;
                    break;
                case "黑":
                    tbColor.Text = "黑";
                    //tb.BackColor = Color.Black;
                    //tb.ForeColor = Color.White;
                    tb.Text = planetNo;
                    break;
                default:
                    tbColor.Text = "";
                    // tb.BackColor = Color.Red;
                    //tb.ForeColor = Color.White;
                    tb.Text = "无车牌";
                    break;
            }

           
        }

        private delegate void InvokeDelegate();
        /// <summary>
        /// 获取实时视频
        /// </summary>
        public void GetLiveVideo()
        {
            try
            {
                if (LivecheckBox.Checked == true && My_MSG_HANDLE[0] == 5 && Lpnr_Handle[0] != IntPtr.Zero)
                {
                    byte[] Livebuf = new byte[300 * 1024];

                    Lpnr.LPNRProgram.LPNR_Lock(Lpnr_Handle[0]);//上锁

                    Lpnr.LPNRProgram.LPNR_GetLiveFrame(Lpnr_Handle[0], Livebuf);

                    Lpnr.LPNRProgram.LPNR_Unlock(Lpnr_Handle[0]);//解锁

                    showVideoToPicture(this.pictureBox_VideoNo1.Width,
                        this.pictureBox_VideoNo1.Height,
                        this.pictureBox_VideoNo1.Location.X,
                        this.pictureBox_VideoNo1.Location.Y,
                        this.pictureBox_VideoNo1,
                        Livebuf);
                    //GuiShowImage(Livebuf);//show image To picture

                }

            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("GetLiveVideo:" + ex.ToString());
            }
        }



        /// <summary>
        /// 获取实时视频
        /// </summary>
        public void GetLiveVideo_2()
        {
            try
            {
                if (LivecheckBox_2.Checked == true && My_MSG_HANDLE[1] == 5 && Lpnr_Handle[1] != IntPtr.Zero)
                {
                    int GetLiveFrame = 0;

                    Lpnr.LPNRProgram.LPNR_Lock(Lpnr_Handle[1]);//上锁
                    int size = Lpnr.LPNRProgram.LPNR_GetLiveFrameSize(Lpnr_Handle[1]);

                    if (size != 0)
                    {
                        //byte[] Livebuf = new byte[size];
                        byte[] Livebuf = new byte[300 * 1024];

                        GetLiveFrame = Lpnr.LPNRProgram.LPNR_GetLiveFrame(Lpnr_Handle[1], Livebuf);

                        if (GetLiveFrame != size)
                        {
                            Lpnr.LPNRProgram.LPNR_Unlock(Lpnr_Handle[1]);//解锁
                        }
                        else
                        {
                            showVideoToPicture(this.pictureBox_VideoNo2.Width,
                                this.pictureBox_VideoNo2.Height,
                                this.pictureBox_VideoNo2.Location.X,
                                this.pictureBox_VideoNo2.Location.Y,
                                this.pictureBox_VideoNo2,
                                Livebuf);
                            //GuiShowImage(Livebuf);//show image To picture
                            Lpnr.LPNRProgram.LPNR_Unlock(Lpnr_Handle[1]);//解锁

                        }
                    }
                    else
                    {
                        // LPNRProgram.LPNR_Unlock(lpip);//解锁
                    }
                }

            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("GetLiveVideo_2:" + ex.ToString());
            }
        }


        /// <summary>
        /// 获取抓拍图片
        /// </summary>
        public void getimageFunction(IntPtr h, int x, int y, PictureBox pb)
        {
            int GetCapturedImageSize = 0;
            try
            {
                Lpnr.LPNRProgram.LPNR_Lock(h);//上锁
                int len = Lpnr.LPNRProgram.LPNR_GetCapturedImageSize(h);//获取抓拍图片大小

                if (len != 0)
                {
                    FlashLog.FlashLogger.Info("获取抓拍图片大小" + len.ToString());

                    byte[] Imagebuf = new byte[len];

                    Lpnr.LPNRProgram.LPNR_Lock(h);//上锁
                    GetCapturedImageSize = Lpnr.LPNRProgram.LPNR_GetCapturedImage(h, Imagebuf);
                    if (GetCapturedImageSize != 0)
                    {
                        FlashLog.FlashLogger.Info("GetCapturedImageSize获取图片返回值" + GetCapturedImageSize.ToString());
                        Lpnr.LPNRProgram.LPNR_Unlock(h);//解锁

                        FlashLog.FlashLogger.Info("Imagebuf大小" + Imagebuf.Length.ToString());

                        showImageToPicture(Imagebuf, x, y, pb);//show image To picture
                    }
                }
                else
                {
                    FlashLog.FlashLogger.Info("图片大小获取失败");
                }
                Lpnr.LPNRProgram.LPNR_Unlock(h);//解锁
            }
            catch (Exception ex)
            {
                throw new Exception("内存操作失败:" + ex.ToString());
            }
        }


        /// <summary>
        /// 获取抓拍图片
        /// </summary>
        public string getimageFunction(IntPtr h, int width, int height, int x, int y, PictureBox pb)
        {
            int GetCapturedImageSize = 0;
            string rec ="";
            try
            {
                Lpnr.LPNRProgram.LPNR_Lock(h);//上锁
                int len = Lpnr.LPNRProgram.LPNR_GetCapturedImageSize(h);//获取抓拍图片大小
                Lpnr.LPNRProgram.LPNR_Unlock(h);//解锁
                if (len != 0)
                {
                    FlashLog.FlashLogger.Info("获取抓拍图片大小" + len.ToString());

                    byte[] Imagebuf = new byte[len];

                    Lpnr.LPNRProgram.LPNR_Lock(h);//上锁
                    GetCapturedImageSize = Lpnr.LPNRProgram.LPNR_GetCapturedImage(h, Imagebuf);
                    Lpnr.LPNRProgram.LPNR_Unlock(h);//解锁

                    if (GetCapturedImageSize != 0)
                    {
                        FlashLog.FlashLogger.Info("GetCapturedImageSize获取图片返回值" + GetCapturedImageSize.ToString());
                        FlashLog.FlashLogger.Info("Imagebuf大小" + Imagebuf.Length.ToString());
                        rec = showImageToPicture(Imagebuf, width, height, x, y, pb);//show image To picture
                    }
                }
                else
                {
                    FlashLog.FlashLogger.Info("抓拍大图大小获取失败");

                    Lpnr.LPNRProgram.LPNR_Lock(h);//上锁
                    len = Lpnr.LPNRProgram.LPNR_GetQuadImageSize(h);//获取抓拍1/4图片大小
                    Lpnr.LPNRProgram.LPNR_Unlock(h);//解锁
                    if (len != 0)//如果抓拍1/4图大小不等于0
                    {
                        FlashLog.FlashLogger.Info("获取抓拍1/4大图大小：" + len.ToString());

                        byte[] Imagebuf = new byte[len];

                        Lpnr.LPNRProgram.LPNR_Lock(h);//上锁
                        int GeQuadImageSize = Lpnr.LPNRProgram.LPNR_GetQuadImage(h, Imagebuf);
                        Lpnr.LPNRProgram.LPNR_Unlock(h);//解锁
                        if (GeQuadImageSize != 0)
                        {
                            FlashLog.FlashLogger.Info("LPNR_GetQuadImage获取1/4图片返回值：" + GeQuadImageSize.ToString());
                            FlashLog.FlashLogger.Info("LPNR_GetQuadImage获取1/4图片Imagebuf大小：" + Imagebuf.Length.ToString());

                            rec = showImageToPicture(Imagebuf, width, height, x, y, pb);//show image To picture
                        }
                        return rec;
                    }
                }
                return rec;
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("getimageFunction:" + ex.ToString());
                return null;
            }
        }


        /// <summary>
        /// 获取彩色图
        /// </summary>
        public void getplatecolorFunction(IntPtr h, PictureBox pb)
        {
            try
            {
                Lpnr.LPNRProgram.LPNR_Lock(h);
                int colorsize = Lpnr.LPNRProgram.LPNR_GetPlateColorImageSize(h);
                Lpnr.LPNRProgram.LPNR_Unlock(h);

                FlashLog.FlashLogger.Info("colorsize" + colorsize.ToString());
                if (colorsize != 0)
                {
                    byte[] buf = new byte[colorsize];
                    Lpnr.LPNRProgram.LPNR_Lock(h);
                    int GetPlateColorImagesize = Lpnr.LPNRProgram.LPNR_GetPlateColorImage(h, buf);
                    Lpnr.LPNRProgram.LPNR_Unlock(h);

                    FlashLog.FlashLogger.Info("获取彩图图片大小" + colorsize.ToString());
                    CommonData.showpicture(pb.Width, pb.Height, pb.Location.X, pb.Location.Y, pb, buf);
          
                    string pic = "vcolor" + DateTime.Now.ToString("HHmmss") + ".bmp";
                    FlashLog.FlashLogger.Info(pic);

                }
                else
                {
                    pb.Image = null;
                    FlashLog.FlashLogger.Info("无彩色图");
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("getplatecolorFunction:" + ex.ToString());
            }
        }


        /// <summary>
        /// 获取二值图
        /// </summary>
        public void getplatBinaryFunction(IntPtr h, PictureBox pb)
        {
            try
            {
                Lpnr.LPNRProgram.LPNR_Lock(h);
                int Binarysize = Lpnr.LPNRProgram.LPNR_GetPlateBinaryImageSize(h);
                Lpnr.LPNRProgram.LPNR_Unlock(h);

                FlashLog.FlashLogger.Info("Binarysize" + Binarysize.ToString());
                if (Binarysize != 0)
                {
                    byte[] buf = new byte[Binarysize];
                    Lpnr.LPNRProgram.LPNR_Lock(h);
                    int a = Lpnr.LPNRProgram.LPNR_GetPlateBinaryImage(h, buf);
                    Lpnr.LPNRProgram.LPNR_Unlock(h);

                    FlashLog.FlashLogger.Info("获取二值图图片大小" + Binarysize.ToString());
                    CommonData.showpicture(pb.Width, pb.Height, pb.Location.X, pb.Location.Y, pb, buf);
               
                    string pic = "vbinary" + DateTime.Now.ToString("HHmmss") + ".bmp";
                    Trace.WriteLogFile(pic);
                }
                else
                {
                    Lpnr.LPNRProgram.LPNR_Unlock(h);
                    pb.Image = null;
                    FlashLog.FlashLogger.Info("无二值化图 ");
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("getplatBinaryFunction:" + ex.ToString());
            }
        }


        public bool doublebit = false;

        public void showVideoToPicture(int witdth, int height, int x, int y, PictureBox pic, byte[] buf)
        {
            try
            {
                //if ( ShowVedioThread != null)
                {
                    if (doublebit == false)
                    {
                        CommonData.showpicture(witdth, height, x, y, pic, buf);
                        //showImageToPicture(840, 540, 16, 60, this.pictureBoxVideo, buf);

                    }
                    else if (doublebit == true)
                    {
                        MemoryStream ms = new MemoryStream(); //新建内存流
                        ms.Write(buf, 0, buf.Length); //赋值
                        pic.SizeMode = PictureBoxSizeMode.StretchImage;
                        pic.Image = Image.FromStream(ms); //读取流中内容
                        ms.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("showVideoToPicture:" + ex.ToString());
            }
        }



        /// <summary>
        /// image至Tpicturebox显示
        /// </summary>
        /// <param name="buf"></param>
        public delegate void SetPicCallback(int witdth, int height, int x, int y, PictureBox pic, byte[] buf);

        public static void showImageToPicture(int witdth, int height, int x, int y, PictureBox pic, byte[] buf)
        {
            //将byte数组 写入picture.image
            try
            {
                if (pic.InvokeRequired)//如果调用控件的线程和创建创建控件的线程不是同一个则为True
                {
                    SetPicCallback d = new SetPicCallback(showImageToPicture);
                    pic.Invoke(d, new object[] { witdth, height, x, y, pic, buf });
                }
                else
                {
                    pic.Width = witdth;
                    pic.Height = height;
                    pic.Location = new Point(x, y);

                    if (buf != null)
                    {
                        MemoryStream ms = new MemoryStream(buf);

                        ms.Position = 0;
                        pic.Image = null;
                        pic.SizeMode = PictureBoxSizeMode.StretchImage;
                        pic.Image = Image.FromStream(ms); //读取流中内容

                        ms.Close();
                    }

                    ////将byte数组 写入picture.image
                    //MemoryStream msw = new MemoryStream(); //新建内存流
                    //if (buf != null)
                    //{
                    //    msw.Write(byteArray, 0, byteArray.Length); //赋值
                    //    pic.Image = null;
                    //    pic.SizeMode = PictureBoxSizeMode.StretchImage;
                    //    pic.Image = Image.FromStream(msw); //读取流中内容
                    //    msw.Dispose();

                    //}
                    //My_MSG_HANDLE = 0;
                }

            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("showImageToPicture:" + ex.ToString());
            }

        }

        /// <summary>
        /// image至Tpicturebox显示
        /// </summary>
        /// <param name="buf"></param>
        public void showImageToPicture(byte[] buf, int x, int y, PictureBox pb)
        {
            pb.Width = 480;
            pb.Height = 340;

            //this.pictureBoxImage.Location = new Point(12, 320);
            pb.Location = new Point(x, y);
            //Common.showpicture(480, 340, x, y, pb, buf);
            CommonData.showpicture(x, y, x, y, pb, buf);

            if (planetAll != string.Empty)
            {
                string plantecolor = planetAll.Substring(0, 1);
                if (plantecolor != "蓝" && plantecolor != "黄" && plantecolor != "绿" && plantecolor != "黑" && plantecolor != "白")
                {
                    planetAll = "整牌据识";

                }
                string pic = "vimage" + DateTime.Now.ToString("HHmmss") + "(" + planetAll + ")" + ".jpg";
                FlashLog.FlashLogger.Info(pic);
                CommonData.SaveTriggerPicture(pic, buf);//保存图片至windows目录中
            }
        }


        /// <summary>
        /// image至Tpicturebox显示
        /// </summary>
        /// <param name="buf"></param>
        public  string showImageToPicture(byte[] buf, int width, int height, int x, int y, PictureBox pb)
        {
            try
            {
                pb.Width = width;
                pb.Height = height;

                //this.pictureBoxImage.Location = new Point(12, 320);
                pb.Location = new Point(x, y);
                //Common.showpicture(480, 340, x, y, pb, buf);
                CommonData.showpicture(width, height, x, y, pb, buf);

                if (planetAll != string.Empty)
                {
                    string plantecolor = planetAll.Substring(0, 1);
                    if (plantecolor != "蓝" && plantecolor != "黄" && plantecolor != "绿" && plantecolor != "黑" && plantecolor != "白")
                    {
                        planetAll = "整牌据识";

                    }
                    string pic = "vimage" + DateTime.Now.ToString("HHmmss") + "(" + planetAll + ")" + ".jpg";
                    FlashLog.FlashLogger.Info(pic);
                    return CommonData.SaveTriggerPicture(pic, buf);//保存图片至windows目录中
                }
            
            }catch(Exception ex){
                FlashLog.FlashLogger.Debug("Exception showImageToPicture " + ex.ToString());
            }
            return null;
        }







        private Ice_Camsdk.ipcsdk.ICE_IPCSDK_OnPlate onPlate;
        private Ice_Camsdk.ipcsdk.ICE_IPCSDK_OnFrame_Planar onFrame;
        private Ice_Camsdk.ipcsdk.ICE_IPCSDK_OnPastPlate onPastPlate;
        private Ice_Camsdk.ipcsdk.ICE_IPCSDK_OnSerialPort onSerialPort;
        private Ice_Camsdk.ipcsdk.ICE_IPCSDK_OnSerialPort_RS232 onSerialPortRS232;
        private Ice_Camsdk.ipcsdk.ICE_IPCSDK_OnDeviceEvent onDeviceEvent;
        private Ice_Camsdk.ipcsdk.ICE_IPCSDK_OnIOEvent onIOEvent;
        //第一路，连接相机，提供了三个连接相机接口的调用方法
        /*
         * 连接接口使用说明：
         * 连接接口共6个：不带密码的：ICE_IPCSDK_OpenPreview， ICE_IPCSDK_Open， ICE_IPCSDK_OpenDevice
         *              带密码的：ICE_IPCSDK_OpenPreview_Passwd， ICE_IPCSDK_Open_Passwd， ICE_IPCSDK_OpenDevice_Passwd
         * 1.当需要视频时，推荐使用：ICE_IPCSDK_OpenPreview；如果是加密相机，则使用ICE_IPCSDK_OpenPreview_Passwd
         * 2.不需要视频时，推荐使用：ICE_IPCSDK_OpenDevice；如果是加密相机，则使用ICE_IPCSDK_OpenDevice_Passwd
         * 3.需要自己做视频显示时，使用：ICE_IPCSDK_Open；如果是加密相机，则使用ICE_IPCSDK_Open_Passwd
         */
        /// <summary>
        /// 初始化华夏智信相机
        /// </summary>
        public string IceCameIP = "";
        public void IceCame_Init()
        {
            try
            {
                if (uiComboBox_LpnrIpNo1.Text.ToString().Trim() == string.Empty)
                {
                    IceCameIP = Common.ConfigHelper.GetConnectionStringConfig("IceCameraIP");
                }
                else
                {
                    IceCameIP = uiComboBox_LpnrIpNo1.Text.ToString().Trim();
                }

                uiComboBox_LpnrIpNo1.Text = IceCameIP;

                int pRet = 0;

                if (LivecheckBox.Checked == true)
                {
                    IntPtr videoHwnd = pictureBox_VideoNo1.Handle;
                    if (videoHwnd != IntPtr.Zero)
                    {
                        //使用不带密码的接口连接相机
                        pUid[0] = Ice_Camsdk.ipcsdk.ICE_IPCSDK_OpenPreview(IceCameIP, 1, 1, (uint)videoHwnd, onPlate, new IntPtr(0));
                        if (pUid[0] == IntPtr.Zero)
                        {
                            UIMessageBox.Show(IceCameIP+"ICE_Carm相机连接失败！", "提示",UIStyle.Red,UIMessageBoxButtons.OK,true,true);
                            return;
                        }

                        Link_InitButton.Enabled = false;
                        Close_OffButton.Enabled = true;

                        m_bExit = false;
                    }
                    else
                    {
                        UIMessageBox.Show("未获得视频播放窗口");
                        return;
                    }

                }

                else if (LivecheckBox.Checked == false)
                {
                    //连接相机，不带视频流
                    pUid[0] = Ice_Camsdk.ipcsdk.ICE_IPCSDK_OpenDevice(IceCameIP);
                    if (pUid[0] != IntPtr.Zero)
                    {
                        Ice_Camsdk.ipcsdk.ICE_IPCSDK_SetPlateCallback(pUid[0], onPlate, new IntPtr(0));//设置车牌识别数据回调

                        //设置断网续传回调
                        Ice_Camsdk.ipcsdk.ICE_IPCSDK_SetPastPlateCallBack(pUid[0], onPastPlate, new IntPtr(0));
                    }
                    else
                    {
                        UIMessageBox.Show(IceCameIP + "ICE_Carm相机连接失败！", "提示", UIStyle.Red, UIMessageBoxButtons.OK, true, true);
                        return;
                    }
                    Link_InitButton.Enabled = false;
                    Close_OffButton.Enabled = true;
                    m_bExit = false;

                }

                FlashLog.FlashLogger.Info("初始化相机 IceCameIP= " + IceCameIP + " " + "pUid[0]=" + pUid[0]);



                //设置断网续传回调
                Ice_Camsdk.ipcsdk.ICE_IPCSDK_SetPastPlateCallBack(pUid[0], onPastPlate, new IntPtr(0));


                bClose[0] = false;

            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("IceCame_Init" + ex.Message.ToString());
            }
        }

        public void IceCame_Init_2()
        {
            try
            {

                if (uiComboBox_LpnrIpNo2.Text.ToString().Trim() == string.Empty)
                {
                    IceCameIP = Common.ConfigHelper.GetConnectionStringConfig("VechileIp_2");
                }
                else
                {
                    IceCameIP = uiComboBox_LpnrIpNo2.Text.ToString().Trim();
                }

                uiComboBox_LpnrIpNo2.Text = IceCameIP;

                int pRet = 0;

                if (LivecheckBox_2.Checked == true)
                {
                    IntPtr videoHwnd = pictureBox_VideoNo2.Handle;
                    if (videoHwnd != IntPtr.Zero)
                    {
                        //使用不带密码的接口连接相机
                        pUid[1] = Ice_Camsdk.ipcsdk.ICE_IPCSDK_OpenPreview(IceCameIP, 1, 1, (uint)videoHwnd, onPlate, new IntPtr(1));
                        if (pUid[1] == IntPtr.Zero)
                        {
                            UIMessageBox.Show(IceCameIP + "ICE_Carm相机连接失败！", "提示", UIStyle.Red, UIMessageBoxButtons.OK, true, true);
                            return;
                        }
                        Link_Init_2Button.Enabled = false;
                        Close_Off_2Button.Enabled = true;
                        m_bExit = false;
                    }
                    else
                    {
                        MessageBox.Show("未获得视频播放窗口");
                        return;
                    }

                }

                else if (LivecheckBox_2.Checked == false)
                {
                    //连接相机，不带视频流
                    pUid[1] = Ice_Camsdk.ipcsdk.ICE_IPCSDK_OpenDevice(IceCameIP);
                    if (pUid[1] != IntPtr.Zero)
                    {
                        Ice_Camsdk.ipcsdk.ICE_IPCSDK_SetPlateCallback(pUid[1], onPlate, new IntPtr(1));//设置车牌识别数据回调

                        //设置断网续传回调
                        Ice_Camsdk.ipcsdk.ICE_IPCSDK_SetPastPlateCallBack(pUid[1], onPastPlate, new IntPtr(1));
                    }
                    else
                    {
                        UIMessageBox.Show(IceCameIP + "ICE_Carm相机连接失败！", "提示", UIStyle.Red, UIMessageBoxButtons.OK, true, true);
                        return;
                    }
                    Link_Init_2Button.Enabled = false;
                    Close_Off_2Button.Enabled = true;
                    m_bExit = false;
                }

                FlashLog.FlashLogger.Info("初始化相机 IceCameIP= " + IceCameIP + " " + "pUid[1]=" + pUid[1]);

                //设置断网续传回调
                Ice_Camsdk.ipcsdk.ICE_IPCSDK_SetPastPlateCallBack(pUid[1], onPastPlate, new IntPtr(1));


                bClose[1] = false;

            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("IceCame_Init_2" + ex.Message.ToString());
            }
        }


        /// <summary>
        /// 初始化华夏智信相机
        /// </summary>
        public void IceCame_Init_All()
        {
            FlashLog.FlashLogger.Info("IceCame_Init_All 初始化");

            Ice_Camsdk.ipcsdk.ICE_IPCSDK_Init(); //调用全局初始化

            if (LivecheckBox.Checked == true)
            {
                onFrame = new Ice_Camsdk.ipcsdk.ICE_IPCSDK_OnFrame_Planar(SDK_OnFrame);//通过该回调函数获得解码出的一帧图像
            }

            onPlate = new Ice_Camsdk.ipcsdk.ICE_IPCSDK_OnPlate(SDK_OnPlate);//通过该回调函数获得实时识别数据
            onPastPlate = new Ice_Camsdk.ipcsdk.ICE_IPCSDK_OnPastPlate(SDK_OnPastPlate);//通过该回调函数获得断网识别数据

    
            onDeviceEvent = new Ice_Camsdk.ipcsdk.ICE_IPCSDK_OnDeviceEvent(SDK_OnDeviceEvent);


            //委托显示车牌信息
            updatePlateInfo = new UpdatePlateInfo(showCount);
            updateDeviceEvent = new UpdateDeviceEvent(showDeviceEvent);
            Ice_Camsdk.ipcsdk.ICE_IPCSDK_SetDeviceEventCallBack(IntPtr.Zero, onDeviceEvent, new IntPtr(0));

        }


        public void showDeviceEvent(string strIP, uint nType, uint ndata1, uint ndata2, uint ndata3, uint ndata4, int nFlag, int road)
        {
           
            string strText = "";
            if (0 == nFlag)
            {
                if (0 == nType)
                {
                    strText = "第" + (road + 1).ToString() + "路 " + strIP + " IO状态改变： " +
                        ndata1.ToString() + ndata2.ToString() + ndata3.ToString() + ndata4.ToString();
                }
             
                return;
            }
            else
            {
                if (0 == nType)
                    strText = strIP + ":当前状态离线";
                else if (1 == nType)
                    strText = strIP + ":当前状态在线";
                else if (2 == nType)
                {
                    //nDeviceEventCount++;
                    //strText = nDeviceEventCount.ToString() + " " + strIP + " IO状态改变： " +
                    //    ndata1.ToString() + ndata2.ToString() + ndata3.ToString() + ndata4.ToString();
                }
            }

            //listBoxInfo.Items.Insert(0, strText);
        }


        public void SDK_OnDeviceEvent(System.IntPtr pvParam,
         [System.Runtime.InteropServices.InAttribute()][System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcIP,
         uint u32EventType, uint u32EventData1, uint u32EventData2, uint u32EventData3, uint u32EventData4)
        {
            IAsyncResult syncResult = this.BeginInvoke(updateDeviceEvent, pcIP, u32EventType, u32EventData1,
                u32EventData2, u32EventData3, u32EventData4, 1, 0);
        }

        public void SDK_OnIOEvent(System.IntPtr pvParam,
            [System.Runtime.InteropServices.InAttribute()][System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcIP,
            uint u32EventType, uint u32IOData1, uint u32IOData2, uint u32IOData3, uint u32IOData4)
        {
            IAsyncResult syncResult = this.BeginInvoke(updateDeviceEvent, pcIP, u32EventType, u32IOData1,
                u32IOData2, u32IOData3, u32IOData4, 0, (int)pvParam);
        }



        //将收到的实时识别数据和断网识别数据显示在界面上
        public void showCount(string strIP, string strNum, string strColor, uint nVehicleColor,
            uint nAlarmType, short nVehiclType, uint nCapTime, int index, string strLogName, Ice_Camsdk.ICE_RECT_S stRect)
        {
            FlashLog.FlashLogger.Info("序号 " + index + " pUid[index] " + pUid[index] + " strIP " + strIP + " 获取到车牌识别结果：" + strColor + " " + strNum);
            if (pUid[index] != IntPtr.Zero)
            {
                if (nCapTime == 0)//实时数据
                {
                    if (strIP == this.uiComboBox_LpnrIpNo1.Text)
                    {
                        string color = "";
                        switch (strColor)
                        {
                            case "黄色":
                                this.PlateText.Text = strNum;
                                color = "黄";
                                //this.PlateText.BackColor = Color.Yellow;
                                //this.PlateText.ForeColor = Color.Black;
                                //this.PlateText.TextAlign = HorizontalAlignment.Center;
                                break;
                            case "蓝色":
                                //this.PlateText.BackColor = Color.Blue;
                                //this.PlateText.ForeColor = Color.White;
                                this.PlateText.Text = strNum;
                                color = "蓝";
                                break;
                            case "白色":
                                //this.PlateText.BackColor = Color.White;
                                //this.PlateText.ForeColor = Color.Black;
                                this.PlateText.Text = strNum;
                                color = "白";
                                break;
                            case "绿色":
                                //this.PlateText.BackColor = Color.PaleGreen;
                                //this.PlateText.ForeColor = Color.Black;
                                this.PlateText.Text = strNum;
                                color = "绿";
                                break;
                            case "黄绿色":
                                //this.PlateText.BackColor = Color.Peru;
                                //this.PlateText.ForeColor = Color.Black;
                                this.PlateText.Text = strNum;
                                color = "秋";
                                break;
                            case "黑色":
                                //this.PlateText.BackColor = Color.Black;
                                //this.PlateText.ForeColor = Color.White;
                                this.PlateText.Text = strNum;
                                color = "黑";
                                break;
                            case "":
                                //this.PlateText.BackColor = Color.Red;
                                //this.PlateText.ForeColor = Color.White;
                                this.PlateText.Text = "无车牌";
                                color = "";
                                break;
                            default:
                                //this.PlateText.BackColor = Color.Red;
                                //this.PlateText.ForeColor = Color.White;
                                this.PlateText.Text = "无车牌";
                                break;
                        }
                        this.uiTextBox_plateColorNo1.Text = color;
                        string textInfo = strIP + " " + "\r\n" + strNum + " " + strColor + " ";
                        this.uiTextBox_InforNo1.Text = "";
                        this.uiTextBox_InforNo1.Text = textInfo  + "\r\n" + "触发方式:" + strAlarmType[nAlarmType] + "\r\n";
                        this.uiTextBox_InforNo1.ForeColor = Color.Blue;
                        
                      
                        //数据显示在控件
                       
                        dataInfoNo[0].plateColor = uiTextBox_plateColorNo1.Text.ToString();
                        dataInfoNo[0].plateNo = color + strNum;//获取车牌号 
                        dataInfoNo[0].serialNumber = dataInfoNo[0].serialNumber + 1;
                        dataInfoNo[0].triggerTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                        dataInfoNo[0].vehicleType = GetVehicleType(this.uiTextBox_vehicleType, dataInfoNo[0].plateNo);
                        DataGridViewAdd(dataInfoNo[0], this.uiDataGridView_laneNo1);
                    }
                    else if (strIP == this.uiComboBox_LpnrIpNo2.Text)
                    {
                        string color = "";
                        switch (strColor)
                        {
                            case "黄色":
                                this.PlateText_2.Text = strNum;
                                color = "黄";
                                //this.PlateText_2.BackColor = Color.Yellow;
                                //this.PlateText_2.ForeColor = Color.Black;
                                //this.PlateText_2.TextAlign = HorizontalAlignment.Center;
                                break;
                            case "蓝色":
                                //this.PlateText_2.BackColor = Color.Blue;
                                //this.PlateText_2.ForeColor = Color.White;
                                this.PlateText_2.Text = strNum;
                                color = "蓝";
                                break;
                            case "白色":
                                //this.PlateText_2.BackColor = Color.White;
                                //this.PlateText_2.ForeColor = Color.Black;
                                this.PlateText_2.Text = strNum;
                                color = "白";
                                break;
                            case "绿色":
                                //this.PlateText_2.BackColor = Color.PaleGreen;
                                //this.PlateText_2.ForeColor = Color.Black;
                                this.PlateText_2.Text = strNum;
                                color = "绿";
                                break;
                            case "黄绿色":
                                //this.PlateText_2.BackColor = Color.Peru;
                                //this.PlateText_2.ForeColor = Color.Black;
                                this.PlateText_2.Text = strNum;
                                color = "秋";
                                break;
                            case "黑色":
                                //this.PlateText_2.BackColor = Color.Black;
                                //this.PlateText_2.ForeColor = Color.White;
                                this.PlateText_2.Text = strNum;
                                color = "黑";
                                break;
                            case "":
                                //this.PlateText_2.BackColor = Color.Red;
                                //this.PlateText_2.ForeColor = Color.White;
                                this.PlateText_2.Text = "无车牌";
                                color = "";
                                break;
                            default:
                                //this.PlateText_2.BackColor = Color.Red;
                                //this.PlateText_2.ForeColor = Color.White;
                                this.PlateText_2.Text = "无车牌";
                                break;
                        }
                        this.uiTextBox_plateColorNo2.Text = color;
                        string textInfo = strIP + " " + "\r\n" + strNum + " " + strColor + " ";
                        this.uiTextBox_InforNo2.Text = "";
                        this.uiTextBox_InforNo2.Text = textInfo + "\r\n" + "触发方式:" + strAlarmType[nAlarmType] + "\r\n";
                        this.uiTextBox_InforNo2.ForeColor = Color.Blue;
                      
                        dataInfoNo[1].plateColor = uiTextBox_plateColorNo2.Text.ToString();
                        dataInfoNo[1].plateNo = color + strNum;//获取车牌号 
                        dataInfoNo[1].serialNumber = dataInfoNo[1].serialNumber + 1;
                        dataInfoNo[1].triggerTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                        dataInfoNo[1].vehicleType = GetVehicleType(this.uiTextBox_vehicleType2, dataInfoNo[1].plateNo);

                        DataGridViewAdd(dataInfoNo[1], this.uiDataGridView_laneNo2);
                    }

                }
                else//断网数据
                {
                    FlashLog.FlashLogger.Info(" 断网数据：");
                    string pastText = ". 断网续传" + strIP + strNum + " " + strColor + " " + strVehicleColor[nVehicleColor + 1];
                    string pastText2 = "    " + strAlarmType[nAlarmType];
                    if (pastText == null || pastText2 == null)
                        return;
                    FlashLog.FlashLogger.Info(" 断网数据：" + pastText);
                }
            }
        }



        //存图
        public void storePic(byte[] picData, string strIP, string strNumber, string strColor, bool bIsPlate, UInt32 nCapTime, float[] fResFuture, string strLogName)
        {

            DateTime dt = new DateTime();
            if (nCapTime == 0)
            {
                dt = DateTime.Now;
            }
            else
            {
                dt = DateTime.Parse("1970-01-01 08:00:00").AddSeconds(nCapTime);
            }

            string strDir = m_strStorePath + @"抓拍_C#\" + strIP + @"\" + dt.ToString("yyyyMMdd");
            if (!Directory.Exists(strDir))
            {
                Directory.CreateDirectory(strDir);
            }

            string strPicName;
            if (strLogName.Length != 0)
                strPicName = strDir + @"\" + dt.ToString("yyyyMMddHHmmss") + "_" + strLogName + "_" + strNumber;
            else
                strPicName = strDir + @"\" + dt.ToString("yyyyMMddHHmmss") + "_" + strNumber;
            if (bIsPlate)//车牌图，图片名后缀加_plate
                strPicName += "_plate";
            //string tmp = strPicName;
            strPicName += ".jpg";
            if (File.Exists(strPicName))//如果图片名存在，则在文件名末尾加数字以分辨，如XXX_1.jpg;XXX_2.jpg
            {
                int count = 1;
                while (count <= 10)
                {
                    strPicName = strDir + @"\" + dt.ToString("yyyyMMddHHmmss") + "_" + strNumber;
                    if (bIsPlate)
                    {
                        strPicName += "_plate";
                    }
                    strPicName += "_" + count.ToString() + ".jpg";

                    if (!File.Exists(strPicName))
                    {
                        break;
                    }
                    count++;
                }
            }
            //存图
            try
            {
                FileStream fs = new FileStream(strPicName, FileMode.Create, FileAccess.Write);
                BinaryWriter bw = new BinaryWriter(fs);
                if (picData != null)
                {
                    bw.Write(picData);
                    bw.Close();
                    fs.Close();
                }

                //这边上报连云港的接口 根据车牌绑定的txid号保持一致
               
                if (strIP == this.uiComboBox_LpnrIpNo1.Text) {

                    string ulid = Utils.DataChage.GetGuid().Replace("-", "");
                    Common.Lyg_SendData.Lyg_ParkingDataInfo parkinfo = Common.Lyg_SendData.ParkInfo_Init(0);//初始化


                    parkinfo.txId = ulid;
                    parkinfo.plateColor = strColor;
                    parkinfo.plate = strNumber;
                    switch (Common.ConfigHelper.GetConnectionStringConfig("LaneType_1"))
                    {
                        case "0": parkinfo.entryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); break;
                        case "1": parkinfo.exitTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); break;
                        default: break;
                    }
                    parkinfo.image1 = Utils.DataChage.ImgToBase64String(strPicName);

                    SendParkData(parkinfo);//更新队列数据
                }
                if (strIP == this.uiComboBox_LpnrIpNo2.Text)
                {
                    string ulid = Utils.DataChage.GetGuid().Replace("-", "");
                    //连云港数据接口上报
                    Common.Lyg_SendData.Lyg_ParkingDataInfo parkinfo = Common.Lyg_SendData.ParkInfo_Init(1);//初始化

                    parkinfo.txId = ulid;
                    parkinfo.plateColor = strColor;
                    parkinfo.plate = strNumber;
                    switch (Common.ConfigHelper.GetConnectionStringConfig("LaneType_2"))
                    {
                        case "0": parkinfo.entryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); break;
                        case "1": parkinfo.exitTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); break;
                        default: break;
                    }
                    parkinfo.image1 = Utils.DataChage.ImgToBase64String(strPicName);

                    SendParkData(parkinfo);//更新队列数据
                }
            }
            catch (System.Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常storePic" + ex.ToString());
            }

            //保存特征码
            if (bIsPlate || null == fResFuture)
                return;

            string strFileName = strDir + @"\" + "vbr_record.txt";

            string strContent = "";

            //将车辆特征码存到字符串中
            for (int i = 0; i < 20; i++)
            {
                if (i != 0)
                    strContent += " ";

                strContent += fResFuture[i].ToString("0.000000");
            }

            //将车辆特征码数据追加到文件名中
            try
            {
                StreamWriter sw = new StreamWriter(strFileName, true, Encoding.Unicode);
                if (null != sw)
                {
                    strContent = dt.ToString("yyyyMMddHHmmss") + "_" + strLogName + "_" + strNumber + ".jpg" + " " + strNumber + " " + strContent + "\r\n";

                    sw.Write(strContent);
                    sw.Close();
                }
            }
            catch (System.Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常storePic" + ex.ToString());
            }

        }


        private bool m_bExit = false;

        public void SDK_OnFrame(System.IntPtr pvParam, uint u32Timestamp, System.IntPtr pu8DataY,
            System.IntPtr pu8DataU, System.IntPtr pu8DataV, int s32LinesizeY, int s32LinesizeU,
            int s32LinesizeV, int s32Width, int s32Height)
        {
            int index = (int)pvParam;
            if (m_bExit || bClose[index])
                return;
            on_frame(u32Timestamp, pu8DataY, pu8DataU, pu8DataV, s32LinesizeY,
                s32LinesizeU, s32LinesizeV, s32Width, s32Height, index);
        }


        /// <summary>
        /// 华夏相机实时处理抓拍信息
        /// </summary>
        /// <param name="bstrIP"></param>
        /// <param name="bstrNumber"></param>
        /// <param name="bstrColor"></param>
        /// <param name="vPicData"></param>
        /// <param name="nPicLen"></param>
        /// <param name="vCloseUpPicData"></param>
        /// <param name="nCloseUpPicLen"></param>
        /// <param name="nSpeed"></param>
        /// <param name="nVehicleType"></param>
        /// <param name="nReserved1"></param>
        /// <param name="nReserved2"></param>
        /// <param name="fPlateConfidence"></param>
        /// <param name="nVehicleColor"></param>
        /// <param name="nPlateType"></param>
        /// <param name="nVehicleDir"></param>
        /// <param name="nAlarmType"></param>
        /// <param name="nCapTime"></param>
        /// <param name="index"></param>
        /// <param name="u32ResultHigh"></param>
        /// <param name="u32ResultLow"></param>
        public void on_plate(string bstrIP, string bstrNumber, string bstrColor, IntPtr vPicData, UInt32 nPicLen,
          IntPtr vCloseUpPicData, UInt32 nCloseUpPicLen, short nSpeed, short nVehicleType, short nReserved1, short nReserved2, Single fPlateConfidence,
          UInt32 nVehicleColor, UInt32 nPlateType, UInt32 nVehicleDir, UInt32 nAlarmType, UInt32 nCapTime, Int32 index, uint u32ResultHigh, uint u32ResultLow)
        {
            try
            {
                if (m_bExit)
                    return;
#if VERSION32
                IntPtr vdcPtr = (IntPtr)u32ResultLow;
#else
            ulong tmp = ((ulong)u32ResultHigh << 32) + (ulong)u32ResultLow;
            IntPtr vdcPtr = (IntPtr)tmp;
#endif
                if (vdcPtr != IntPtr.Zero)
                {

                    //将数据拷贝到ICE_VDC_PICTRUE_INFO_S结构体
                    vdcInfo = (Ice_Camsdk.ICE_VDC_PICTRUE_INFO_S)Marshal.PtrToStructure(vdcPtr, typeof(Ice_Camsdk.ICE_VDC_PICTRUE_INFO_S));

                    //获得车款结构体指针，并拷贝
                    if (vdcInfo.pstVbrResult != IntPtr.Zero)
                    {

                        vbrResult = (Ice_Camsdk.ICE_VBR_RESULT_S)Marshal.PtrToStructure(vdcInfo.pstVbrResult, typeof(Ice_Camsdk.ICE_VBR_RESULT_S));
                        if (vbrResult.szLogName.Length == 0)
                            vbrResult.szLogName = "未知";
                        //委托，用于显示识别数据(showCount),vdcInfo.stPlateInfo表示车牌信息
                        this.BeginInvoke(updatePlateInfo, bstrIP, bstrNumber, bstrColor,
                            nVehicleColor, nAlarmType, nVehicleType, nCapTime, index, vbrResult.szLogName, vdcInfo.stPlateInfo.stPlateRect);
                    }
                    else
                        this.BeginInvoke(updatePlateInfo, bstrIP, bstrNumber, bstrColor,
                            nVehicleColor, nAlarmType, nVehicleType, nCapTime, index, "", vdcInfo.stPlateInfo.stPlateRect);//委托，用于显示识别数据(showCount),vdcInfo.stPlateInfo表示车牌信息
                }
                else

                    this.BeginInvoke(updatePlateInfo, bstrIP, bstrNumber, bstrColor,
                            nVehicleColor, nAlarmType, nVehicleType, nCapTime, index, "", null);//委托，用于显示识别数据(showCount)


                if (nPicLen > 0)//全景图数据长度不为0
                {
                    IntPtr ptr2 = (IntPtr)vPicData;
                    byte[] dataAlljpg = new byte[nPicLen];
                    Marshal.Copy(ptr2, dataAlljpg, 0, dataAlljpg.Length);//拷贝图片数据
                                                                         //存图
                                                                         //FlashLog.FlashLogger.Info("hasIceCamera 开始保存图片");
                    if (vdcInfo.pstVbrResult != IntPtr.Zero)
                    {
                        storePic(dataAlljpg, bstrIP, bstrNumber, bstrColor, false, nCapTime, vbrResult.fResFeature, vbrResult.szLogName);
                    }
                    else
                    {
                        storePic(dataAlljpg, bstrIP, bstrNumber, bstrColor, false, nCapTime, null, "");
                    }
                    //显示图片
                    showIcPic(bstrIP, dataAlljpg, 0);

                }


                //车牌特写图
                if (nCloseUpPicLen > 0)//车牌图数据长度不为0
                {
                    IntPtr ptr = (IntPtr)vCloseUpPicData;
                    byte[] datajpg = new byte[nCloseUpPicLen];
                    Marshal.Copy(ptr, datajpg, 0, datajpg.Length);//拷贝图片数据
                                                                  //存图
                    if (vdcInfo.pstVbrResult != IntPtr.Zero)
                        storePic(datajpg, bstrIP, bstrNumber, bstrColor, true, nCapTime, null, vbrResult.szLogName);
                    else
                        storePic(datajpg, bstrIP, bstrNumber, bstrColor, true, nCapTime, null, "");
                    //显示车牌特写图

                    showIcPic(bstrIP, datajpg, 1);
                    FlashLog.FlashLogger.Info("车牌图数据长度不为0，获取抓拍图片数据显示 ");

                }

            }
            catch (Exception ex) {
                FlashLog.FlashLogger.Error("Exception on_plate " + ex.ToString());
            }
        }

        /// <summary>
        /// 显示图片至上位机
        /// </summary>
        /// <param name="IPAddress"></param>
        /// <param name="data"></param>
        /// <param name="type"> 0 为抓拍图 1 为 车牌特写图</param>
        public void showIcPic(string IPAddress, byte[] data, int type)
        {
            try
            {
                //跨线程访问
                Thread objThread = new Thread(new ThreadStart(delegate
                {
                    Control.CheckForIllegalCrossThreadCalls = false;//添加这一句即可


                    if (IPAddress == uiComboBox_LpnrIpNo1.Text.ToString())
                    {
                        //Common.showpicture(480, 340, 12, 320, this.pictureBoxImage, data);//显示抓拍图片至pic

                        if (type == 0)
                        {
                            CommonData.showpicture(this.pictureBox_SnapImage1.Width,
                                this.pictureBox_SnapImage1.Height,
                                this.pictureBox_SnapImage1.Location.X,
                                this.pictureBox_SnapImage1.Location.Y,
                                this.pictureBox_SnapImage1, data);//显示抓拍图片至pic
                        }
                        else if (type == 1)
                        {
                            CommonData.showpicture(this.ColorpictureBox.Width,
                                   this.ColorpictureBox.Height,
                                   this.ColorpictureBox.Location.X,
                                   this.ColorpictureBox.Location.Y,
                                   this.ColorpictureBox, data);//显示车牌特写图片至pic
                        }
                    }
                    else if (IPAddress == uiComboBox_LpnrIpNo2.Text.ToString())
                    {
                        //Common.showpicture(480, 340,572, 320, this.pictureBoxImage_2, data);//显示抓拍图片至pic
                        if (type == 0)
                        {
                            CommonData.showpicture(this.pictureBox_SnapImage2.Width,
                            this.pictureBox_SnapImage2.Height,
                            this.pictureBox_SnapImage2.Location.X,
                            this.pictureBox_SnapImage2.Location.Y,
                            this.pictureBox_SnapImage2, data);//显示抓拍图片至pic
                        }
                        else if (type == 1)
                        {
                            CommonData.showpicture(this.ColorpictureBox_2.Width,
                               this.ColorpictureBox_2.Height,
                               this.ColorpictureBox_2.Location.X,
                               this.ColorpictureBox_2.Location.Y,
                               this.ColorpictureBox_2, data);//显示车牌特写图片至pic
                        }
                    }

                }));
                objThread.Start();
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常showIcPic " + ex.ToString());
            }
        }



        //实时抓拍
        public void SDK_OnPlate(System.IntPtr pvParam,
                    [System.Runtime.InteropServices.InAttribute()][System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcIP,
                    [System.Runtime.InteropServices.InAttribute()][System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcNumber,
                    [System.Runtime.InteropServices.InAttribute()][System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcColor,
                    System.IntPtr pcPicData, uint u32PicLen, System.IntPtr pcCloseUpPicData, uint u32CloseUpPicLen,
                    short nSpeed, short nVehicleType, short nReserved1, short nReserved2,
                    float fPlateConfidence, uint u32VehicleColor, uint u32PlateType, uint u32VehicleDir, uint u32AlarmType,
                    uint u32SerialNum, uint uCapTime, uint u32ResultHigh, uint u32ResultLow)
        {
            int index = (int)pvParam;
            if (m_bExit || bClose[index])
                return;
            on_plate(pcIP, pcNumber, pcColor, pcPicData, u32PicLen, pcCloseUpPicData, u32CloseUpPicLen,
                nSpeed, nVehicleType, nReserved1, nReserved2, fPlateConfidence,
                u32VehicleColor, u32PlateType, u32VehicleDir, u32AlarmType, 0, index, u32ResultHigh, u32ResultLow);


        }

        //断网续传
        public void SDK_OnPastPlate(System.IntPtr pvParam,
            [System.Runtime.InteropServices.InAttribute()][System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcIP,
            uint u32CapTime,
            [System.Runtime.InteropServices.InAttribute()][System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcNumber,
            [System.Runtime.InteropServices.InAttribute()][System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pcColor,
            System.IntPtr pcPicData, uint u32PicLen, System.IntPtr pcCloseUpPicData, uint u32CloseUpPicLen, short s16PlatePosLeft,
            short s16PlatePosTop, short s16PlatePosRight, short s16PlatePosBottom, float fPlateConfidence, uint u32VehicleColor,
            uint u32PlateType, uint u32VehicleDir, uint u32AlarmType, uint u32Reserved1, uint u32Reserved2, uint u32Reserved3,
            uint u32Reserved4)
        {
            int index = (int)pvParam;
            if (m_bExit || bClose[index])
                return;
            on_plate(pcIP, pcNumber, pcColor, pcPicData, u32PicLen, pcCloseUpPicData, u32CloseUpPicLen,
                s16PlatePosLeft, s16PlatePosTop, s16PlatePosRight, s16PlatePosBottom, fPlateConfidence,
                u32VehicleColor, u32PlateType, u32VehicleDir, u32AlarmType, u32CapTime, index, u32Reserved2, u32Reserved3);
        }


        private int[] frame_count = new int[4] { 0, 0, 0, 0 };

        public void on_frame(UInt32 u32Timestamp,
            IntPtr pu8DataY, IntPtr pu8DataU, IntPtr pu8DataV,
            Int32 s32LinesizeY, Int32 s32LinesizeU, Int32 s32LinesizeV,
            Int32 s32Width, Int32 s32Height, Int32 i)
        {
            if (m_bExit)
                return;

            mutex.WaitOne();
            string strDir = m_strStorePath + @"抓拍_C#Frame\" + IceCameIP + @"\" + DateTime.Now.ToString("yyyyMMdd");
            if (!Directory.Exists(strDir))
            {
                Directory.CreateDirectory(strDir);
            }

            string strPicName = strDir + @"\" + "test.bmp";

            if (0 == (frame_count[i] % 30))
            {

                try
                {
                    //拷贝数据
                    byte[] datay = new byte[s32Width * s32Height];
                    for (int j = 0; j < s32Height; j++)
                        Marshal.Copy((IntPtr)pu8DataY + j * s32LinesizeY, datay, j * s32Width, s32Width);

                    byte[] datau = new byte[s32Width * s32Height / 4];
                    for (int j = 0; j < s32Height / 2; j++)
                        Marshal.Copy((IntPtr)pu8DataU + j * s32LinesizeU, datau, j * s32Width / 2, s32Width / 2);

                    byte[] datav = new byte[s32Width * s32Height / 4];
                    for (int j = 0; j < s32Height / 2; j++)
                        Marshal.Copy((IntPtr)pu8DataV + j * s32LinesizeV, datav, j * s32Width / 2, s32Width / 2);

                    byte[] rgb24 = new byte[s32Width * s32Height * 3];

                    util.Convert(s32Width, s32Height, datay, datau, datav, ref rgb24);

                    //存图
                    FileStream fs = new FileStream(strPicName, FileMode.Create, FileAccess.Write);
                    BinaryWriter bw = new BinaryWriter(fs);

                    bw.Write('B');
                    bw.Write('M');
                    bw.Write(rgb24.Length + 54);
                    bw.Write(0);
                    bw.Write(54);
                    bw.Write(40);
                    bw.Write(s32Width);
                    bw.Write(s32Height);
                    bw.Write((ushort)1);
                    bw.Write((ushort)24);
                    bw.Write(0);
                    bw.Write(rgb24.Length);
                    bw.Write(0);
                    bw.Write(0);
                    bw.Write(0);
                    bw.Write(0);

                    bw.Write(rgb24, 0, rgb24.Length);
                    bw.Close();
                    fs.Close();

                }
                catch (System.Exception ex)
                {
                    //MessageBox.Show("frame" + ex.Message);
                }

                frame_count[i] = 0;
            }
            frame_count[i]++;
            mutex.ReleaseMutex();
        }


        public class util
        {
            private static int width;
            private static int height;
            private static int length;
            private static int v;  //v值的起始位置
            private static int u;  //u值的起始位置
            private static int rdif, invgdif, bdif;
            private static int[] Table_fv1;
            private static int[] Table_fv2;
            private static int[] Table_fu1;
            private static int[] Table_fu2;
            private static int[] rgb = new int[3];
            private static int m, n, i, j, hfWidth;
            private static bool addHalf = true;
            private static int py;
            private static int pos, pos1;//dopod 595 图像调整
            private static byte temp;

            public static void YV12ToRGB(int iWidth, int iHeight)
            {
                Table_fv1 = new int[256] { -180, -179, -177, -176, -174, -173, -172, -170, -169, -167, -166, -165, -163, -162, -160, -159, -158, -156, -155, -153, -152, -151, -149, -148, -146, -145, -144, -142, -141, -139, -138, -137, -135, -134, -132, -131, -130, -128, -127, -125, -124, -123, -121, -120, -118, -117, -115, -114, -113, -111, -110, -108, -107, -106, -104, -103, -101, -100, -99, -97, -96, -94, -93, -92, -90, -89, -87, -86, -85, -83, -82, -80, -79, -78, -76, -75, -73, -72, -71, -69, -68, -66, -65, -64, -62, -61, -59, -58, -57, -55, -54, -52, -51, -50, -48, -47, -45, -44, -43, -41, -40, -38, -37, -36, -34, -33, -31, -30, -29, -27, -26, -24, -23, -22, -20, -19, -17, -16, -15, -13, -12, -10, -9, -8, -6, -5, -3, -2, 0, 1, 2, 4, 5, 7, 8, 9, 11, 12, 14, 15, 16, 18, 19, 21, 22, 23, 25, 26, 28, 29, 30, 32, 33, 35, 36, 37, 39, 40, 42, 43, 44, 46, 47, 49, 50, 51, 53, 54, 56, 57, 58, 60, 61, 63, 64, 65, 67, 68, 70, 71, 72, 74, 75, 77, 78, 79, 81, 82, 84, 85, 86, 88, 89, 91, 92, 93, 95, 96, 98, 99, 100, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 122, 123, 124, 126, 127, 129, 130, 131, 133, 134, 136, 137, 138, 140, 141, 143, 144, 145, 147, 148, 150, 151, 152, 154, 155, 157, 158, 159, 161, 162, 164, 165, 166, 168, 169, 171, 172, 173, 175, 176, 178 };
                Table_fv2 = new int[256] { -92, -91, -91, -90, -89, -88, -88, -87, -86, -86, -85, -84, -83, -83, -82, -81, -81, -80, -79, -78, -78, -77, -76, -76, -75, -74, -73, -73, -72, -71, -71, -70, -69, -68, -68, -67, -66, -66, -65, -64, -63, -63, -62, -61, -61, -60, -59, -58, -58, -57, -56, -56, -55, -54, -53, -53, -52, -51, -51, -50, -49, -48, -48, -47, -46, -46, -45, -44, -43, -43, -42, -41, -41, -40, -39, -38, -38, -37, -36, -36, -35, -34, -33, -33, -32, -31, -31, -30, -29, -28, -28, -27, -26, -26, -25, -24, -23, -23, -22, -21, -21, -20, -19, -18, -18, -17, -16, -16, -15, -14, -13, -13, -12, -11, -11, -10, -9, -8, -8, -7, -6, -6, -5, -4, -3, -3, -2, -1, 0, 0, 1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 9, 10, 10, 11, 12, 12, 13, 14, 15, 15, 16, 17, 17, 18, 19, 20, 20, 21, 22, 22, 23, 24, 25, 25, 26, 27, 27, 28, 29, 30, 30, 31, 32, 32, 33, 34, 35, 35, 36, 37, 37, 38, 39, 40, 40, 41, 42, 42, 43, 44, 45, 45, 46, 47, 47, 48, 49, 50, 50, 51, 52, 52, 53, 54, 55, 55, 56, 57, 57, 58, 59, 60, 60, 61, 62, 62, 63, 64, 65, 65, 66, 67, 67, 68, 69, 70, 70, 71, 72, 72, 73, 74, 75, 75, 76, 77, 77, 78, 79, 80, 80, 81, 82, 82, 83, 84, 85, 85, 86, 87, 87, 88, 89, 90, 90 };
                Table_fu1 = new int[256] { -44, -44, -44, -43, -43, -43, -42, -42, -42, -41, -41, -41, -40, -40, -40, -39, -39, -39, -38, -38, -38, -37, -37, -37, -36, -36, -36, -35, -35, -35, -34, -34, -33, -33, -33, -32, -32, -32, -31, -31, -31, -30, -30, -30, -29, -29, -29, -28, -28, -28, -27, -27, -27, -26, -26, -26, -25, -25, -25, -24, -24, -24, -23, -23, -22, -22, -22, -21, -21, -21, -20, -20, -20, -19, -19, -19, -18, -18, -18, -17, -17, -17, -16, -16, -16, -15, -15, -15, -14, -14, -14, -13, -13, -13, -12, -12, -11, -11, -11, -10, -10, -10, -9, -9, -9, -8, -8, -8, -7, -7, -7, -6, -6, -6, -5, -5, -5, -4, -4, -4, -3, -3, -3, -2, -2, -2, -1, -1, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 20, 20, 20, 21, 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 40, 41, 41, 41, 42, 42, 42, 43, 43 };
                Table_fu2 = new int[256] { -227, -226, -224, -222, -220, -219, -217, -215, -213, -212, -210, -208, -206, -204, -203, -201, -199, -197, -196, -194, -192, -190, -188, -187, -185, -183, -181, -180, -178, -176, -174, -173, -171, -169, -167, -165, -164, -162, -160, -158, -157, -155, -153, -151, -149, -148, -146, -144, -142, -141, -139, -137, -135, -134, -132, -130, -128, -126, -125, -123, -121, -119, -118, -116, -114, -112, -110, -109, -107, -105, -103, -102, -100, -98, -96, -94, -93, -91, -89, -87, -86, -84, -82, -80, -79, -77, -75, -73, -71, -70, -68, -66, -64, -63, -61, -59, -57, -55, -54, -52, -50, -48, -47, -45, -43, -41, -40, -38, -36, -34, -32, -31, -29, -27, -25, -24, -22, -20, -18, -16, -15, -13, -11, -9, -8, -6, -4, -2, 0, 1, 3, 5, 7, 8, 10, 12, 14, 15, 17, 19, 21, 23, 24, 26, 28, 30, 31, 33, 35, 37, 39, 40, 42, 44, 46, 47, 49, 51, 53, 54, 56, 58, 60, 62, 63, 65, 67, 69, 70, 72, 74, 76, 78, 79, 81, 83, 85, 86, 88, 90, 92, 93, 95, 97, 99, 101, 102, 104, 106, 108, 109, 111, 113, 115, 117, 118, 120, 122, 124, 125, 127, 129, 131, 133, 134, 136, 138, 140, 141, 143, 145, 147, 148, 150, 152, 154, 156, 157, 159, 161, 163, 164, 166, 168, 170, 172, 173, 175, 177, 179, 180, 182, 184, 186, 187, 189, 191, 193, 195, 196, 198, 200, 202, 203, 205, 207, 209, 211, 212, 214, 216, 218, 219, 221, 223, 225 };
                width = iWidth;
                height = iHeight;
                length = iWidth * iHeight;
                v = length;//nYLen
                u = v + (length >> 2);
                hfWidth = iWidth >> 1;
                addHalf = true;
            }

            public static bool Convert(int cwidth, int cheight, byte[] yv12y, byte[] yv12u, byte[] yv12v, ref byte[] rgb24)
            {
                try
                {
                    YV12ToRGB(cwidth, cheight);
                    if (yv12y.Length == 0 || rgb24.Length == 0)
                        return false;
                    m = -width;
                    n = -hfWidth;
                    for (int y = 0; y < height; y++)
                    {
                        if (y == 139)
                        {
                        }
                        m += width;
                        if (addHalf)
                        {
                            n += hfWidth;
                            addHalf = false;
                        }
                        else
                        {
                            addHalf = true;
                        }
                        for (int x = 0; x < width; x++)
                        {
                            i = m + x;
                            j = n + (x >> 1);
                            py = (int)yv12y[i];
                            rdif = Table_fv1[(int)yv12v[j]];
                            invgdif = Table_fu1[(int)yv12u[j]] + Table_fv2[(int)yv12v[j]];
                            bdif = Table_fu2[(int)yv12u[j]];

                            rgb[2] = py + rdif;//R
                            rgb[1] = py - invgdif;//G
                            rgb[0] = py + bdif;//B

                            j = v - width - m + x;
                            i = (j << 1) + j;

                            // copy this pixel to rgb data
                            for (j = 0; j < 3; j++)
                            {

                                if (rgb[j] >= 0 && rgb[j] <= 255)
                                {
                                    rgb24[i + j] = (byte)rgb[j];
                                }
                                else
                                {
                                    rgb24[i + j] = (byte)((rgb[j] < 0) ? 0 : 255);
                                }

                            }
                            if (x % 4 == 3)
                            {
                                pos = (m + x - 1) * 3;
                                pos1 = (m + x) * 3;
                                temp = rgb24[pos];
                                rgb24[pos] = rgb24[pos1];
                                rgb24[pos1] = temp;

                                temp = rgb24[pos + 1];
                                rgb24[pos + 1] = rgb24[pos1 + 1];
                                rgb24[pos1 + 1] = temp;

                                temp = rgb24[pos + 2];
                                rgb24[pos + 2] = rgb24[pos1 + 2];
                                rgb24[pos1 + 2] = temp;
                            }
                        }
                    }
                }
                catch (Exception e)
                {

                    MessageBox.Show(e.Message);
                }
                return true;
            }

        }

        public void ClearPic_1()
        {
            this.ColorpictureBox.Image = null;
            this.BinarypictureBox.Image = null;
            this.PlateText.Text = null;
            this.confidenceText.Text = null;

        }
        public void ClearPic_2()
        {
            this.ColorpictureBox_2.Image = null;
            this.BinarypictureBox_2.Image = null;
            this.PlateText_2.Text = null;
            this.confidenceText_2.Text = null;

        }

        private void CloseIce_Camsdk(IntPtr p)
        {
            if (p == IntPtr.Zero)
                return;

            bClose[0] = true;
            try
            {
                FlashLog.FlashLogger.Info("CloseIce_Camsdk 关闭摄像机连接句柄" + p.ToString());


                if (p.ToString() == pUid[0].ToString())
                {
                    mutexThread.WaitOne();
                    Ice_Camsdk.ipcsdk.ICE_IPCSDK_Close(p);//断开连接

                    p = IntPtr.Zero;
                    pUid[0] = IntPtr.Zero;
                    this.pictureBox_VideoNo1.Image = (System.Drawing.Image)(Properties.Resources.VideoRegion); ;//.Refresh();//关闭视频  刷新
                    this.pictureBox_SnapImage1.Image = (System.Drawing.Image)(Properties.Resources.ImageRegion); ;//.Refresh();//关闭视频  刷新
                    mutexThread.ReleaseMutex();
                    FlashLog.FlashLogger.Info("CloseIce_Camsdk 关闭摄像机连接句柄 完成");
                }
                else if (p.ToString() == pUid[1].ToString())
                {
                    mutexThread.WaitOne();
                    Ice_Camsdk.ipcsdk.ICE_IPCSDK_Close(p);//断开连接

                    p = IntPtr.Zero;
                    pUid[1] = IntPtr.Zero;
                    this.pictureBox_VideoNo2.Image = (System.Drawing.Image)(Properties.Resources.VideoRegion);//.Refresh();//关闭视频  刷新
                    this.pictureBox_SnapImage2.Image = (System.Drawing.Image)(Properties.Resources.ImageRegion);//.Refresh();//关闭视频  刷新
                    mutexThread.ReleaseMutex();
                    FlashLog.FlashLogger.Info("CloseIce_Camsdk 关闭摄像机连接句柄 完成");
                }

            }
            catch (System.Exception ex)
            {
                throw new Exception(ex.Message);
            }

            frame_count[0] = 0;

        }

        private void 车道视频监控_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                park_work_run = false;

                ClearPic_1();
                ClearPic_2();

                if (Common.ConfigHelper.GetConnectionStringConfig("hasWelcomeLed") == "yes") //WJdll
                {
                    if (WelcomeLedIphwnd != IntPtr.Zero)
                    {
                        Led.TFIProgram.TFI_Close(WelcomeLedIphwnd);
                        Led.TFIProgram.TFI_Destroy(WelcomeLedIphwnd);
                    }
                }

                /*
                    if (H264_Handle[0] != IntPtr.Zero)
                    {
                        H264.H264Decoder.H264DEC_Terminate(H264_Handle[0]);
                    }
                 */
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "0") //WJdll
                {

                    if (Common.ConfigHelper.GetConnectionStringConfig("hasH264") == "yes")
                    {
                        if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Terminate(H264_Handle[0]))
                        {
                            H264_Handle[0] = IntPtr.Zero;
                        }
                    }
                    if (Lpnr_Handle[0] != IntPtr.Zero)
                    {
                        if (Lpnr.LPNRProgram.LPNR_COM_init(Lpnr_Handle[0], 0))
                        {
                            FlashLog.FlashLogger.Info("串口透传初始化关闭");
                        }

                        if (Lpnr.LPNRProgram.LPNR_Terminate(Lpnr_Handle[0]))
                        {
                            Lpnr_Handle[0] = IntPtr.Zero;
                            My_MSG_HANDLE[0] = 0;
                            FlashLog.FlashLogger.Info("关闭摄像机连接");
                        }

                    }
                    else
                    {
                        FlashLog.FlashLogger.Info("摄像机返回句柄为0");
                    }


                }
                /*
                if (H264_Handle[1] != IntPtr.Zero)
                {
                    H264.H264Decoder.H264DEC_Terminate(H264_Handle[1]);
                }
                */
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "0")
                {
                    if (Common.ConfigHelper.GetConnectionStringConfig("hasH264") == "yes")
                    {
                        if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Terminate(H264_Handle[1]))
                        {
                            H264_Handle[1] = IntPtr.Zero;
                        }
                    }

                    if (Lpnr_Handle[1] != IntPtr.Zero)
                    {
                        if (Lpnr.LPNRProgram.LPNR_COM_init(Lpnr_Handle[1], 0))
                        {
                            FlashLog.FlashLogger.Info("串口透传初始化关闭");
                        }

                        if (Lpnr.LPNRProgram.LPNR_Terminate(Lpnr_Handle[1]))
                        {
                            Lpnr_Handle[1] = IntPtr.Zero;
                            My_MSG_HANDLE[1] = 0;
                            FlashLog.FlashLogger.Info("关闭摄像机连接");
                        }

                    }
                    else
                    {
                        FlashLog.FlashLogger.Info("摄像机返回句柄为0");
                    }


                }


                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "1" || Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "1") //hasIceCamera
                {
                    m_bExit = true;

                    if (threadTrigger != null)
                    {
                        threadTrigger.Abort();
                        threadTrigger = null;
                    }
                    if (threadOpenGate != null)
                    {
                        threadOpenGate.Abort();
                        threadOpenGate = null;
                    }
                    if (threadStatus != null)
                    {
                        threadStatus.Abort();
                        threadStatus = null;
                    }
                    if (threadOpenGate2 != null)
                    {
                        threadOpenGate2.Abort();
                        threadOpenGate2 = null;
                    }


                    for (int i = 0; i < 2; i++)//2台相机
                    {
                        FlashLog.FlashLogger.Info("关闭ice摄像机返回句柄:" + pUid[i].ToString());
                        if (pUid[i] != IntPtr.Zero)
                        {
                            Ice_Camsdk.ipcsdk.ICE_IPCSDK_Close(pUid[i]);
                            pUid[i] = IntPtr.Zero;
                        }
                    }
                    //mutexThread.ReleaseMutex();
                    mutex.Close();
                    mutex = null;
                    mutexThread.Close();
                    mutexThread = null;
                    Ice_Camsdk.ipcsdk.ICE_IPCSDK_Fini(); //调用全局释放   

                }

                if (Common.ConfigHelper.GetConnectionStringConfig("hasDaHua") == "yes" || Common.ConfigHelper.GetConnectionStringConfig("hasHIKVISION") == "yes")
                {
                    release();
                }


                GetVedio = false;

                FlashLog.FlashLogger.Instance().AbortThread(); //关闭log4

            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常LPNRTool_FormClosing" + ex.ToString());
            }
        }



        private void Close_OffButton_Click(object sender, EventArgs e)
        {
            Close_OffButton.Enabled = false;
            Link_InitButton.Enabled = true;

            bool _isclose = false;
            try
            {
                ClearPic_1();

                if (client != null)
                {
                    client.Close();
                }
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "0") //WJdll
                {
                    if (Lpnr_Handle[0] != IntPtr.Zero)
                    {
                        if (H264_Handle[0] != IntPtr.Zero)
                        {
                            if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "0")
                            {
                                if (H264.H264Decoder.H264DEC_Terminate(H264_Handle[0]))
                                {
                                    H264_Handle[0] = IntPtr.Zero; vedioBit[0] = false;
                                }
                            }
                            else if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "1")
                            {
                                if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Terminate(H264_Handle[0]))
                                {
                                    H264_Handle[0] = IntPtr.Zero; vedioBit[0] = false;
                                }
                            }
                        }

                        if (Lpnr.LPNRProgram.LPNR_COM_init(Lpnr_Handle[0], 0))
                        {
                            FlashLog.FlashLogger.Info("串口透传初始化关闭");
                        }

                        _isclose = Lpnr.LPNRProgram.LPNR_Terminate(Lpnr_Handle[0]);
                        if (_isclose == true)
                        {
                            Lpnr_Handle[0] = IntPtr.Zero;
                            My_MSG_HANDLE[0] = 0;
                            FlashLog.FlashLogger.Info("关闭摄像机连接");
                        }
                        if (picturehWnd[0] != IntPtr.Zero)
                        {
                            //HVDLL.CloseHv(picturehWnd[0]);

                        }
                        this.pictureBox_VideoNo1.Image = (System.Drawing.Image)(Properties.Resources.VideoRegion);//.Refresh();//关闭视频  刷新
                        this.pictureBox_SnapImage1.Image = (System.Drawing.Image)(Properties.Resources.ImageRegion);//.Refresh();//关闭视频  刷新
                    }
                    else
                    {
                        FlashLog.FlashLogger.Info("摄像机返回句柄为0");
                    }
                }
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "1")
                {
                    CloseIce_Camsdk(pUid[0]);
                }

                if (Common.ConfigHelper.GetConnectionStringConfig("hasDaHua") == "yes" || Common.ConfigHelper.GetConnectionStringConfig("hasHIKVISION") == "yes")
                {
                    //release();
                }

            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("CloseButton_Click:" + ex.ToString());
            }
        }

        private void Close_Off_2Button_Click(object sender, EventArgs e)
        {
            Close_Off_2Button.Enabled = false;
            Link_Init_2Button.Enabled = true;

            bool _isclose = false;
            try
            {
                ClearPic_2();

                if (client != null)
                {
                    client.Close();
                }
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "0")
                {
                    if (Lpnr_Handle[1] != IntPtr.Zero)
                    {
                        if (H264_Handle[1] != IntPtr.Zero)
                        {
                            if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "0")
                            {
                                if (H264.H264Decoder.H264DEC_Terminate(H264_Handle[1]))
                                {
                                    H264_Handle[1] = IntPtr.Zero; vedioBit[1] = false;
                                }
                            }
                            else if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "1")
                            {
                                if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Terminate(H264_Handle[1]))
                                {
                                    H264_Handle[1] = IntPtr.Zero; vedioBit[1] = false;
                                }
                            }
                        }
                        if (Lpnr.LPNRProgram.LPNR_COM_init(Lpnr_Handle[1], 0))
                        {
                            FlashLog.FlashLogger.Info("串口透传初始化关闭");
                        }

                        _isclose = Lpnr.LPNRProgram.LPNR_Terminate(Lpnr_Handle[1]);
                        if (_isclose == true)
                        {
                            Lpnr_Handle[1] = IntPtr.Zero;
                            My_MSG_HANDLE[1] = 0;
                            FlashLog.FlashLogger.Info("关闭摄像机连接");
                        }
                        if (picturehWnd[1] != IntPtr.Zero)
                        {
                            //HVDLL.CloseHv(picturehWnd[1]);

                        }
                        this.pictureBox_VideoNo2.Image = (System.Drawing.Image)(Properties.Resources.VideoRegion);//.Refresh();//关闭视频  刷新
                        this.pictureBox_SnapImage2.Image = (System.Drawing.Image)(Properties.Resources.ImageRegion);//.Refresh();//关闭视频  刷新
                    }
                    else
                    {
                        FlashLog.FlashLogger.Info("摄像机返回句柄为0");
                    }
                }


                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "1")
                {
                    CloseIce_Camsdk(pUid[1]);
                }
                if (Common.ConfigHelper.GetConnectionStringConfig("hasDaHua") == "yes" || Common.ConfigHelper.GetConnectionStringConfig("hasHIKVISION") == "yes")
                {
                    //release();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }



        public bool m_StopListen = false;
        /// <summary>
        /// 连接车道，开启UDPserver
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Link_LaneButton_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                client.Close();
            }

            udptest.StartUdpReceive();

        }

        private void Link_Lane_2Button_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                client.Close();
            }

            udptest.StartUdpReceive();
        }


        /// <summary>
        /// Udp监听
        /// </summary>
        public void StartUdpRec()
        {

            if (!IsUdpcRecvStart) // 未监听的情况，开始监听
            {
                IPEndPoint localIpep = new IPEndPoint(IPAddress.Parse("172.16.13.145"), 10031); // 本机IP和监听端口号
                udpcRecv = new UdpClient(localIpep);
                thrRecv = new Thread(ReceiveMessage);
                thrRecv.Start();
                IsUdpcRecvStart = true;
                FlashLog.FlashLogger.Info("UDP监听器已成功启动");
            }
            else // 正在监听的情况，终止监听
            {
                thrRecv.Abort(); // 必须先关闭这个线程，否则会异常
                udpcRecv.Close();
                IsUdpcRecvStart = false;
                FlashLog.FlashLogger.Info("UDP监听器已成功关闭");
            }
        }

        private UdpClient udpcRecv;
        /// <summary>
        /// 开关：在监听UDP报文阶段为true，否则为false
        /// </summary>
        bool IsUdpcRecvStart = false;
        /// <summary>
        /// 线程：不断监听UDP报文
        /// </summary>
        Thread thrRecv;



        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="obj"></param>
        private void ReceiveMessage(object obj)
        {
            IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse("172.16.13.220"), 10031);
            while (true)
            {
                try
                {
                    byte[] bytRecv = udpcRecv.Receive(ref remoteIpep);
                    string message = Encoding.Unicode.GetString(bytRecv, 0, bytRecv.Length);
                    Trace.WriteLogFile(string.Format("{0}[{1}]", remoteIpep, message));
                }
                catch (Exception ex)
                {
                    break;
                }
            }
        }


        private static byte[] result = new byte[1024];
        public Socket clientSocket = null;
        public string serverip = Common.ConfigHelper.GetConnectionStringConfig("SerIp");
        public int serverport = int.Parse(Common.ConfigHelper.GetConnectionStringConfig("SerPort"));

        public void tcpsend(string sendMessage)
        {
            //设定服务器IP地址  
            IPAddress ip = IPAddress.Parse(serverip);
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, serverport)); //配置服务器IP与端口  
                FlashLog.FlashLogger.Info("连接后台服务器成功");
            }
            catch
            {
                FlashLog.FlashLogger.Info("连接服务器失败，请按回车键退出！");
                return;
            }

            try
            {
                Thread.Sleep(100);    //等待1秒钟  
                FlashLog.FlashLogger.Info("发送 " + sendMessage);
                clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
            catch
            {
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();

            }
        }





        public byte[] MAGIC;
        private void btnSuccess_Click(object sender, EventArgs e)
        {
            if (lanetype == "1")
            {
                FlashLog.FlashLogger.Info("http发送控制抬杆命令");

                CommonGoupFunctionHttpJson(LaneName[0], "抬杆", UIStyle.Blue, "http://" + LaneIp[0] + ":81/lane/ctr", http_alb[0].ToString());

            }
            else
            {
                if (UIMessageBox.Show("是否控制抬杆？", "提示", UIStyle.Blue, UIMessageBoxButtons.OKCancel, true))
                {
                    if (lanetype == "0")
                    {
                        FlashLog.FlashLogger.Info("udp发送控制抬杆命令");
                        byte[] buf = { 0x34, 0x12, 0xcd, 0xab, 0x01, 0x00, 0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6E, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x3D, 0x6D, 0x69, 0x75, 0x6B, 0x65 };
                        udptest.StartUdpSend(buf);
                        //this.EntryFallingpictureBox.Visible = false;
                        //this.EntryRailingpictureBox.Visible = true;

                        //byte[] MAGIC = new byte[4]{0x34, 0x12 ,0xcd ,0xab};
                        //byte[] SN = new byte[4] { 0x01, 0x00, 0x00, 0x00 };
                        //byte[] Code = new byte[]
                        //MAGIC = new byte[] { 0x34, 0x12, 0xcd, 0xab, 0x01, 0x00, 0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6E, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x3D, 0x6D, 0x69, 0x75, 0x6B, 0x65 };
                    }
                    else if (lanetype == "2")
                    {
                        string str = LaneIp[0] + "|0";
                        tcpsend(str);
                    }

                }
                else
                {
                    FlashLog.FlashLogger.Info("取消控制抬杆");
                }
            }
        }


        private void FallDown_Button_Click(object sender, EventArgs e)
        {
            if (lanetype == "1")
            {
                FlashLog.FlashLogger.Info("http发送控制落杆命令");

                CommonGoupFunctionHttpJson(LaneName[0], "落杆", UIStyle.Red, "http://" + LaneIp[0] + ":81/lane/ctr", http_alb[1].ToString());
            }
            else
            {
                if (UIMessageBox.Show("是否控制落杆？", "提示", UIStyle.Red, UIMessageBoxButtons.OKCancel, true))
                {
                    if (lanetype == "0")
                    {
                        FlashLog.FlashLogger.Info("udp发送控制落杆命令");
                        byte[] buf = { 0x34, 0x12, 0xcd, 0xab, 0x01, 0x00, 0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6E, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x3D, 0x6D, 0x69, 0x75, 0x6B, 0x65 };
                        udptest.StartUdpSend(buf);
                        //this.EntryFallingpictureBox.Visible = true;
                        //this.EntryRailingpictureBox.Visible = false;
                    }

                    else if (lanetype == "2")
                    {
                        string str = LaneIp[0] + "|1";
                        tcpsend(str);
                    }
                }
                else
                {
                    FlashLog.FlashLogger.Info("取消控制落杆");
                }
            }
        }


        private void RaiseUp_2Button_Click(object sender, EventArgs e)
        {
            if (lanetype == "1")
            {
                FlashLog.FlashLogger.Info("http发送控制抬杆命令");
                CommonGoupFunctionHttpJson(LaneName[1], "抬杆", UIStyle.Blue, "http://" + LaneIp[1] + ":81/lane/ctr", http_alb[0].ToString());
            }
            else
            {
                if (UIMessageBox.Show("是否控制抬杆？", "提示", UIStyle.Blue, UIMessageBoxButtons.OKCancel, true))
                {
                    if (lanetype == "0")
                    {
                        FlashLog.FlashLogger.Info("udp发送控制抬杆命令");
                        byte[] buf = { 0x34, 0x12, 0xcd, 0xab, 0x01, 0x00, 0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6E, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x3D, 0x6D, 0x69, 0x75, 0x6B, 0x65 };
                        udptest.StartUdpSend_2(buf);
                        //this.ExitFallingpictureBox.Visible = false;
                        //this.ExitRailingpictureBox.Visible = true;
                    }

                    else if (lanetype == "2")
                    {
                        string str = LaneIp[1] + "|0";
                        tcpsend(str);
                    }
                }
                else
                {
                    FlashLog.FlashLogger.Info("取消控制抬杆");
                }
            }
        }


        private void FallDown_2Button_Click(object sender, EventArgs e)
        {
            if (lanetype == "1")
            {
                FlashLog.FlashLogger.Info("http发送控制落杆命令");

                CommonGoupFunctionHttpJson(LaneName[1], "落杆", UIStyle.Red, "http://" + LaneIp[1] + ":81/lane/ctr", http_alb[1].ToString());
            }
            else
            {
                if (UIMessageBox.Show("是否控制落杆？", "提示", UIStyle.Red, UIMessageBoxButtons.OKCancel, true))
                {
                    if (lanetype == "0")
                    {
                        FlashLog.FlashLogger.Info("udp发送控制落杆命令");
                        byte[] buf = { 0x34, 0x12, 0xcd, 0xab, 0x01, 0x00, 0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6E, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x3D, 0x6D, 0x69, 0x75, 0x6B, 0x65 };
                        udptest.StartUdpSend_2(buf);
                        //this.ExitFallingpictureBox.Visible = true;
                        //this.ExitRailingpictureBox.Visible = false;
                    }

                    else if (lanetype == "2")
                    {
                        string str = LaneIp[1] + "|1";
                        tcpsend(str);
                    }

                }
                else
                {
                    FlashLog.FlashLogger.Info("取消控制落杆");
                }
            }
        }





        /// <summary>
        /// http 控制抬杆公共方法
        /// </summary>
        /// <param name="postUrl"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public void CommonGoupFunctionHttpJson(string lanename, string ctrl, UIStyle st, string postUrl, string param)
        {
            try
            {
                if (UIMessageBox.Show("是否控制 " + lanename + " " + ctrl + "？", "提示", st, UIMessageBoxButtons.OKCancel, true))
                {

                    CommonGoupFunctionHttpJson_common(postUrl, param);
                }
                else
                {
                    FlashLog.FlashLogger.Info("取消控制" + ctrl);

                }

            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("CommonGoupFunctionHttpJson" + ex.ToString());
            }
        }


        public void CommonGoupFunctionHttpJson_common(string postUrl, string param)
        {
            try
            {
                MyThreadClass myThread = new MyThreadClass(postUrl, param);

                Thread httpthread = new Thread(myThread.ThreadMain);
                ThreadList.Add(httpthread);
                httpthread.Start();
                httpthread.IsBackground = true;
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常CommonGoupFunctionHttpJson_common" + ex.ToString());
            }
        }




        public void sendMsg()
        {
            try
            {
                FlashLog.FlashLogger.Info("发送线程开启");

                LaneIP[0] = Common.ConfigHelper.GetConnectionStringConfig("VechileIp");
                int udpport = 10041;
                EndPoint point = new IPEndPoint(IPAddress.Parse(LaneIP[0]), udpport);

                //client.SendTo(Encoding.UTF8.GetBytes(msg),point);
                if (_issendudp == true)
                {
                    client.SendTo(MAGIC, point);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        public void ReciveMsg()
        {
            try
            {
                FlashLog.FlashLogger.Info("接受线程开启");
                _issendudp = false;
                Trace.WriteLogFile(_isrecudp.ToString());
                while (_isrecudp == true)
                {
                    EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
                    byte[] buffer = new byte[20];
                    int length = client.ReceiveFrom(buffer, ref point);//接收数据报
                    string message = CommonData.byteToHexStr(buffer);
                    //string message = Encoding.UTF8.GetString(buffer, 0, length);
                    FlashLog.FlashLogger.Info("收到UDP消息是" + message);
                }
                FlashLog.FlashLogger.Info("接受线程关闭");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void SetSysTime_button_Click(object sender, EventArgs e)
        {
            bool SynctimeBit = false;
            try
            {
                if (SynctimeBit == false && Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "0")
                {
                    if (SynctimeBit = Lpnr.LPNRProgram.LPNR_SyncTime(Lpnr_Handle[0]))
                    {
                        FlashLog.FlashLogger.Info("更新抓拍机系统时间成功");
                    }
                }

                else if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "1")
                {
                    if (IntPtr.Zero == pUid[0])
                        return;
                    //时间同步，相机采用utc时间
                    Ice_Camsdk.ipcsdk.ICE_IPCSDK_SyncTime(pUid[0], (UInt16)DateTime.UtcNow.Year, (byte)DateTime.UtcNow.Month,
                    (byte)DateTime.UtcNow.Day, (byte)DateTime.UtcNow.Hour, (byte)DateTime.UtcNow.Minute, (byte)DateTime.UtcNow.Second);
                    FlashLog.FlashLogger.Info("更新ice抓拍机系统时间成功");
                }
            }
            catch (Exception ex)
            {

                throw new Exception("对时间失败" + ex.Message);
            }
        }

        /// <summary>
        /// 软触发
        /// </summary>
        public void Tpr_Soft_trrger(IntPtr h)
        {
            try
            {
                //lpnr动态库
                if (h != IntPtr.Zero)
                {
                    if (Lpnr.LPNRProgram.LPNR_SoftTrigger(h))
                    {
                        softTriggerCount++;
                        FlashLog.FlashLogger.Info("完成" + softTriggerCount + "次软触发");
                    }
                }
                else
                {
                    FlashLog.FlashLogger.Info("抓拍机未能正确初始化 句柄为0");
                }
            }

            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }



        public void Ice_Soft_trrger(IntPtr h)
        {

            FlashLog.FlashLogger.Info("相机软触发开启");

            if (h != IntPtr.Zero)
            {
                StringBuilder strNum = new StringBuilder(32);
                StringBuilder strColor = new StringBuilder(64);
                uint len = 0;
                //IntPtr pLen = Marshal.AllocHGlobal(32);
                byte[] pdata = new byte[1048576];
                uint success = Ice_Camsdk.ipcsdk.ICE_IPCSDK_Trigger(h, strNum, strColor, pdata, 1048576, ref len);//软触发
                if (1 == success && len > 0)
                {
                    //    if (len > 0)
                    //    {
                    //        byte[] datajpg2 = new byte[len];
                    //        Array.Copy(pdata, 0, datajpg2, 0, datajpg2.Length);//拷贝图片数据
                    //        storePic(datajpg2, textBoxIP1.Text, strNum.ToString(), false, 0);//存图
                    //    }
                    //    labelPlate1.Text = count[0] + " " + strNum.ToString() + " " + strColor.ToString();
                    //    count[0]++;
                    FlashLog.FlashLogger.Info("hasIceCamera 软触发 完成");
                }
                pdata = null;
                strNum = null;
                strColor = null;


            }


        }



        private void TriggerSnap_Button_Click(object sender, EventArgs e)
        {
            try
            {
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "0")
                {
                    Tpr_Soft_trrger(Lpnr_Handle[0]);
                }
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "1")
                {
                    Ice_Soft_trrger(pUid[0]);
                }
            }

            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("TriggerButton_Click:" + ex.ToString());
            }
        }

        private void SetSysTime_2button_Click(object sender, EventArgs e)
        {
            bool SynctimeBit = false;

            try
            {
                if (SynctimeBit == false && Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "0")
                {
                    if (SynctimeBit = Lpnr.LPNRProgram.LPNR_SyncTime(Lpnr_Handle[1]))
                    {
                        FlashLog.FlashLogger.Info("更新抓拍机系统时间成功");
                    }
                }

                else if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "1")
                {
                    if (IntPtr.Zero == pUid[1])
                        return;
                    //时间同步，相机采用utc时间
                    Ice_Camsdk.ipcsdk.ICE_IPCSDK_SyncTime(pUid[1], (UInt16)DateTime.UtcNow.Year, (byte)DateTime.UtcNow.Month,
                    (byte)DateTime.UtcNow.Day, (byte)DateTime.UtcNow.Hour, (byte)DateTime.UtcNow.Minute, (byte)DateTime.UtcNow.Second);
                    FlashLog.FlashLogger.Info("更新ice抓拍机系统时间成功");
                }
            }
            catch (Exception ex)
            {

                throw new Exception("对时间失败" + ex.Message);
            }
        }

        private void TriggerSnap_2Button_Click(object sender, EventArgs e)
        {
            try
            {
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "0")
                {
                    Tpr_Soft_trrger(Lpnr_Handle[1]);
                }
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "1")
                {
                    Ice_Soft_trrger(pUid[1]);
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("TriggerSnap_2Button_Click:" + ex.ToString());
            }
        }



        /// <summary>
        /// 跨线程显示至textbox
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="str"></param>
        public static void showhandle(Sunny.UI.UITextBox bt, string str)
        {
            try
            {
                if (bt.InvokeRequired)
                {
                    if (bt != null)
                    {
                        if (str != null)
                        {
                            // 当一个控件的InvokeRequired属性值为真时，说明有一个创建它以外的线程想访问它
                            Action<string> actionDelegate = (x) => { bt.Text = x.ToString(); };
                            // 或者
                            // Action<string> actionDelegate = delegate(string txt) { this.label2.Text = txt; };
                            bt.Invoke(actionDelegate, str);
                        }

                        else
                        {
                            bt.Text = str.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("showhandle 异常" + ex.ToString());
            }
        }



        private void uiSwitch_Feelt1_ValueChanged(object sender, bool value)
        {
            try
            {
                feeltbit[0] = this.uiSwitch_Feelt1.Active == true ? true : false;

                if (lanetype == "1")
                {
                    if (feeltbit[0])
                    {

                        FlashLog.FlashLogger.Info("队列模式开 " + LaneName[0] + " " + LaneIp[0]);
                        CommonGoupFunctionHttpJson_common("http://" + LaneIp[0] + ":81/lane/ctr", http_alb[2].ToString());
                        //udptest.udpSendMsg(LaneIp[0], Feeltgoup_buf);
                    }
                    else
                    {
                        FlashLog.FlashLogger.Info("队列模式关 " + LaneName[0] + " " + LaneIp[0]);
                        //udptest.udpSendMsg(LaneIp[0], Feeltgodn_buf);
                        CommonGoupFunctionHttpJson_common("http://" + LaneIp[0] + ":81/lane/ctr", http_alb[3].ToString());

                    }
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常uiSwitch_Feelt1_ValueChanged " + ex.ToString());
            }
        }

        private void uiSwitch_Feelt2_ValueChanged(object sender, bool value)
        {
            try
            {
                feeltbit[1] = this.uiSwitch_Feelt2.Active == true ? true : false;
                if (lanetype == "1")
                {
                    if (feeltbit[1])
                    {

                        FlashLog.FlashLogger.Info("队列模式 udp发送车队模式开 " + LaneName[1] + " " + LaneIp[1]);
                        //udptest.udpSendMsg(LaneIp[1], Feeltgoup_buf);
                        CommonGoupFunctionHttpJson_common("http://" + LaneIp[1] + ":81/lane/ctr", http_alb[2].ToString());

                    }
                    else
                    {
                        FlashLog.FlashLogger.Info("队列模式 udp发送车队模式关 " + LaneName[1] + " " + LaneIp[1]);
                        //udptest.udpSendMsg(LaneIp[1], Feeltgodn_buf);
                        CommonGoupFunctionHttpJson_common("http://" + LaneIp[1] + ":81/lane/ctr", http_alb[3].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常uiSwitch_Feelt2_ValueChanged " + ex.ToString());
            }
        }

        private void LivecheckBox_ValueChanged(object sender, bool value)
        {

            if (LivecheckBox.Checked == true)
            {
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "0")
                {
                    if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "0")
                    {
                        H264_Handle[0] = H264.H264Decoder.H264DEC_Init(CameraIP[0], 1);
                        if (H264_Handle[0] != IntPtr.Zero)
                        {
                            H264.H264Decoder.H264DEC_SetWinMsg(H264_Handle[0], this.Handle, MY_MSG_BEGIN_H264);//消息接收窗口)
                            vedioBit[0] = true;
                        }
                    }
                    else if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "1")
                    {
                        //20220413 采用最新video 动态库
                        H264_Handle[0] = RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Create(CameraIP[0], 1);

                        if (H264_Handle[0] != IntPtr.Zero)
                        {
                            FlashLog.FlashLogger.Info("VIDEO_Create 初始化成功 " + H264_Handle[0].ToString());

                            if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_SetRenderWindow(H264_Handle[0], this.pictureBox_VideoNo1.Handle)) 
                            {
                                if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Start(H264_Handle[0]))
                                {
                                    FlashLog.FlashLogger.Info("VIDEO_Start 启动成功");
                                    vedioBit[0] = true;
                                }
                            }
                        }
                    }
                }

                else if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "1")
                {
                    //To do华夏相机视频接口初始化
                }
            }
            else
            {
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "0")
                {
                    if (H264_Handle[0] != IntPtr.Zero)
                    {
                        if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "0")
                        {
                            if (H264.H264Decoder.H264DEC_Terminate(H264_Handle[0]))
                            {
                                FlashLog.FlashLogger.Info("H264释放成功"); H264_Handle[0] = IntPtr.Zero; vedioBit[0] = false;
                            }
                        }
                        else if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "1")
                        {
                            if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Terminate(H264_Handle[0]))
                            {
                                H264_Handle[0] = IntPtr.Zero;
                                vedioBit[0] = false;
                            }
                        }
                    }
                }
                else if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_1") == "1")
                {
                    //To do华夏相机视频接口关闭


                }
            }

        }

        private void LivecheckBox_2_ValueChanged(object sender, bool value)
        {

            if (LivecheckBox_2.Checked == true)
            {
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "0")
                {
                    if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "0")
                    {
                        H264_Handle[1] = H264.H264Decoder.H264DEC_Init(CameraIP[1], 1);
                        if (H264_Handle[1] != IntPtr.Zero)
                        {
                            H264.H264Decoder.H264DEC_SetWinMsg(H264_Handle[1], this.Handle, MY_MSG_BEGIN_H264_2);//消息接收窗口)
                            vedioBit[1] = true;
                        }
                    }
                    else if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "1")
                    {
                        H264_Handle[1] = RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Create(CameraIP[1], 1);
                        if (H264_Handle[1] != IntPtr.Zero)
                        {
                            FlashLog.FlashLogger.Info("VIDEO_Create 初始化成功 " + H264_Handle[1].ToString());

                            if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_SetRenderWindow(H264_Handle[1], this.pictureBox_VideoNo2.Handle)) 
                            {
                                if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Start(H264_Handle[1]))
                                {
                                    FlashLog.FlashLogger.Info("VIDEO_Start 启动成功");
                                    vedioBit[1] = true;
                                }
                            }
                        }
                    }
                }
                else if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "1")
                {
                    //To do华夏相机视频接口初始化
                }

            }
            else
            {
                if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "0")
                {
                    if (H264_Handle[1] != IntPtr.Zero)
                    {
                        if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "0")
                        {
                            if (H264.H264Decoder.H264DEC_Terminate(H264_Handle[1]))
                            {
                                FlashLog.FlashLogger.Info("H264释放成功"); H264_Handle[1] = IntPtr.Zero;
                                vedioBit[1] = false;
                            }
                        }
                        else if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "1")
                        {
                            if (RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Terminate(H264_Handle[1]))
                            {
                                H264_Handle[1] = IntPtr.Zero;
                                vedioBit[1] = false;
                            }
                        }
                    }

                }
                else if (Common.ConfigHelper.GetConnectionStringConfig("VechileType_2") == "1")
                {
                    //To do华夏相机视频接口关闭


                }

            }


        }




        private void uiSymbolButton_videoStart_Click(object sender, EventArgs e)
        {
            if (H264_Handle[0] != IntPtr.Zero & vedioBit[0] == false)
            {
                if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "0")
                {
                    H264.H264Decoder.H264DEC_Resume(H264_Handle[0]);
                    vedioBit[0] = true;
                }

                else if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "1")
                {
                    RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Start(H264_Handle[0]);
                    vedioBit[0] = true;
                }
            }
        }

        private void uiSymbolButton_videoStop_Click(object sender, EventArgs e)
        {
            if (H264_Handle[0] != IntPtr.Zero & vedioBit[0] == true)
            {
                if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "0")
                {
                    H264.H264Decoder.H264DEC_Suspend(H264_Handle[0]);
                    vedioBit[0] = false;
                }

                else if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "1")
                {
                    RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Stop(H264_Handle[0]);
                    vedioBit[0] = false;
                }
            }
        }

        private void uiSymbolButton_videoStart2_Click(object sender, EventArgs e)
        {
            if (H264_Handle[1] != IntPtr.Zero & vedioBit[1] == false)
            {
                if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "0")
                {
                    H264.H264Decoder.H264DEC_Resume(H264_Handle[1]);
                    vedioBit[1] = true;
                }

                else if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "1")
                {
                    RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Start(H264_Handle[1]);
                    vedioBit[1] = true;
                }
            }
        }

        private void uiSymbolButton_videoStop2_Click(object sender, EventArgs e)
        {
            if (H264_Handle[1] != IntPtr.Zero & vedioBit[1] == true)
            {
                if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "0")
                {
                    H264.H264Decoder.H264DEC_Suspend(H264_Handle[1]);
                    vedioBit[1] = false;
                }
                else if (Common.ConfigHelper.GetConnectionStringConfig("h264Type") == "1")
                {
                    RWLPNRVideo.RWLPNRVideoProgram.VIDEO_Stop(H264_Handle[1]);
                    vedioBit[1] = false;
                }
            }
        }


        private void uiButton1_Click(object sender, EventArgs e)
        {
            try
            {
                Image imgBackgroud = pictureBox_SnapImage1.Image; //背景图
                Image imgForegroud = ColorpictureBox.Image; //前景图
                Graphics g = Graphics.FromImage(imgBackgroud);
                g.DrawImage(imgForegroud,
                    new Rectangle(0, 0, imgForegroud.Width, imgForegroud.Height),
                    new Rectangle(0, 0, imgForegroud.Width, imgForegroud.Height),
                    GraphicsUnit.Pixel);
                g.Dispose();
                //pictureBox3.Image = imgBackgroud; //叠加的图
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Error("uiButton1_Click Exception " + ex.ToString());
            }
        }


    }



    public class MyThreadClass
    {
        private string postUrl;
        private string param;

        public MyThreadClass(string postUrl, string param)
        {
            this.postUrl = postUrl;
            this.param = param;
        }

        public void ThreadMain()
        {
            try
            {
                Encoding encoding = Encoding.GetEncoding("utf-8");

                string jsonstr = Utils.DataChage.ConvertJsonString(param);
                FlashLog.FlashLogger.Info("Http请求地址：" + postUrl);
                //FlashLog.FlashLogger.Info("参数:  " + jsonstr);

                HttpWebResponse response = Utils.HttpPOstDemo.CreatePostHttpResponseJson(postUrl, jsonstr, encoding);

                if (response != null)
                {
                    Stream stream = response.GetResponseStream();   //获取响应的字符串流
                    StreamReader sr = new StreamReader(stream);     //创建一个stream读取流
                    string receivehtml = sr.ReadToEnd();            //从头读到尾，放到字符串html

                    FlashLog.FlashLogger.Info("后台返回值：" + receivehtml);
                }
                else
                {
                    FlashLog.FlashLogger.Info("请求失败:  " + "\r\n");
                }

            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("CommonGoupFunctionHttpJson_other" + ex.ToString());
            }

        }





    }





    /// <summary>
    /// 获取到车牌请求后台 只传参不需要返回值的引用格式
    /// </summary>
    public class requestThreadClass
    {
        public Sunny.UI.UITextBox Tb;//用于判断是哪个窗体的值
        public string postUrl;
        public string Guid;
        public string Ulid;
        public string Plate;
        public string Voucher;
        public string TriggerTime;
        public string recVehicleType;
        public requestThreadClass(Sunny.UI.UITextBox tb, string inOuturl, string guid, string ulid, string plate, string voucher, string triggerTime)
        {
            this.Tb = tb;
            this.postUrl = inOuturl;
            this.Guid = guid;
            this.Ulid = ulid;
            this.Plate = plate;
            this.Voucher = voucher;
            this.TriggerTime = triggerTime;
        }

        public void requestThreadMain()
        {
            Common.RequestObject req = new Common.RequestObject();

            req.postUrl = postUrl;
            req.Guid = Guid;
            req.Ulid = Ulid;
            req.Plate = Plate;
            req.Voucher = Voucher;
            req.TriggerTime = TriggerTime;

            try
            {
                Encoding encoding = Encoding.GetEncoding("utf-8");

                //json格式参数
                StringBuilder data = new StringBuilder();
                data.Append("{");
                data.Append("\"Guid\":\"" + req.Guid + "\",");
                data.Append("\"Ulid\":\"" + req.Ulid + "\",");
                data.Append("\"Plate\":\"" + req.Plate + "\",");
                data.Append("\"Voucher\":\"" + req.Voucher + "\",");
                data.Append("\"VoucherType\":\"" + req.VoucherType + "\",");
                data.Append("\"TriggerTime\":\"" + req.TriggerTime + "\"");
                data.Append("}");

                string param = Utils.DataChage.ConvertJsonString(data.ToString());

                FlashLog.FlashLogger.Info("后台请求postUrl：" + req.postUrl);
                HttpWebResponse response = http.HTTPPost.CreatePostHttpResponseJson(req.postUrl, param, encoding);

                if (response != null)
                {
                    Stream stream = response.GetResponseStream();   //获取响应的字符串流
                    StreamReader sr = new StreamReader(stream);     //创建一个stream读取流
                    string recHtml = sr.ReadToEnd();            //从头读到尾，放到字符串html
                    FlashLog.FlashLogger.Info("后台返回值:  " + recHtml + "\r\n");
                    if (recHtml != null)
                    {
                        recVehicleType = handleRequestJson(Tb, recHtml);

                        FlashLog.FlashLogger.Info("车辆类型：" + recVehicleType);
                    }
                }
                else
                {
                    FlashLog.FlashLogger.Debug("后台请求失败");
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("SelectState " + ex.Message.ToString() + "\r\n");
            }

        }

        /// <summary>
        /// 处理后台返回的json
        /// </summary>
        /// <param name="rec"></param>
        public string handleRequestJson(Sunny.UI.UITextBox tb, string rec)
        {
            try
            {
                AskInParkingObject askin = JsonConvert.DeserializeObject<AskInParkingObject>(rec);
                string vehicletype = askin.VehicleType;

                switch (tb.Name)
                {
                    case "PlateText":
                        break;
                    case "PlateText_2":
                        break;
                    default: break;

                }

                return vehicletype;
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常handleRequestJson " + ex.ToString());
                return "";
            }

        }

    }

    /// <summary>
    /// 后台返回值
    /// </summary>
    public class AskInParkingObject
    {
        public string msg { get; set; }
        public string code { get; set; }
        public string AllowPass { get; set; }
        public string Explain { get; set; }
        public string VehicleType { get; set; }
        public string Voice { get; set; }
    }

    public class AskOutParkingObject
    {
        public string msg { get; set; }
        public string InSn { get; set; }
        public string code { get; set; }
        public string AllowPass { get; set; }
        public string Explain { get; set; }
        public string VehicleType { get; set; }
        public string Voice { get; set; }
    }






    //ThreadWithState 类里包含了将要执行的任务以及执行任务的方法
    public class ThreadWithState
    {
        //要用到的属性，也就是我们要传递的参数
        private string boilerplate;
        private int value;

        //包含参数的构造函数
        public ThreadWithState(string text, int number)
        {
            boilerplate = text;
            value = number;

        }

        //要丢给线程执行的方法，本处无返回类型就是为了能让ThreadStart来调用
        public void ThreadProc()
        {
            try
            {
                //这里就是要执行的任务,本处只显示一下传入的参数
                FlashLog.FlashLogger.Debug("======这里就是要执行的任务,本处只显示一下传入的参数： " + boilerplate + "  " + value);


                
                //UINotifierHelper.ShowNotifier(boilerplate, UINotifierType.OK, UILocalize.WarningTitle, false, 5000);
                UINotifierHelper.ShowNotifier("123", UINotifierType.OK, UILocalize.WarningTitle, false, 5000);

                FlashLog.FlashLogger.Debug("======");
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("Exception ThreadProc " + ex.ToString());
            }
        }


        public void threadRun()
        {
            try {

                MethodInvoker mi = new MethodInvoker(delegate
                {
                    ThreadProc();
                 
                });
               mi.BeginInvoke(null,null);

                //MethodInvoker In = new MethodInvoker(ThreadProc);
                //In.BeginInvoke(null, null);
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("Exception threadRun " + ex.ToString());
            }
        }

       
    }






    }
